<?php
/**
 * 根据不同状态获取 赛事数据
 * User: Jun.peng
 * Date: 2019/4/4
 * Time: 10:57
 */

namespace Biz\Match;
use Biz\Match\GetOddsData;
use App\Sports\Model\St_zq_league as leagueModel;
use App\Sports\Model\St_zq_competition as matchModel;
use App\Sports\Model\St_zq_odds as ZQoddsModel;
use App\Sports\Model\St_wq_odds as WQoddsModel;
use App\Sports\Model\St_bq_odds as BQoddsModel;
use App\Sports\Model\St_lq_odds as LQoddsModel;

class GetmatchData {

    public function __construct() {
        $this->getOddsData = new GetOddsData();
        $this->commonFunction =  C()->get('commonFunction');
    }

    /**
     * @param $ret 提交参数
     * @param $source 数据源条件
     * @return array
     * @throws \Exception
     * 获取不同状态下的赛事相关数据
     */
    public function typeData($ret,$source){
        //根据球类代码 获取相关model
        $models = $this->commonFunction->getModels($ret['game_code']);
        $model_match = $models['model_match'];

        //获取 不同状态的查询条件
        $where = $this->commonFunction->getState($ret['type_code'],$model_match,$ret['game_code']);

        //根据联赛id查询
        if(!empty($ret['lg_id'])){
            $lg_id = $ret['lg_id'];
        }
        //根据搜索查询
        if(!empty($ret['search'])){
            $search = $ret['search'];
        }

        switch ($ret['type_code']){
            case 'StRollBall'://滚球
                $data = $this->getRollBall($source,$models,$where,$ret,$search);
                break;
            case 'StSoon'://即将
                $oddsTypeWhere = [
                    [$models['model_odds'].'.is_stringscene','=',0],
                ];
                $data = $this->getSoon($source,$models,$where,$lg_id,$ret,$search,$oddsTypeWhere);
                break;
            case 'StToday'://今日
                $oddsTypeWhere = [
                    [$models['model_odds'].'.is_stringscene','=',0],
                ];
                $data = $this->getToday($source,$models,$where,$lg_id,$search,$oddsTypeWhere);
                break;
            case 'StMorningPlate'://早盘
                //默认当天
                if(empty($ret['match_date'])){
                    // $match_date = date("Y-m-d");
                    $match_date = '';

                }else{
                    if($ret['match_date'] != 'other'){
                        $match_date = $ret['match_date'];
                    }else{
                        $match_date = 'other';
                    }
                }
                $oddsTypeWhere = [
                    [$models['model_odds'].'.is_stringscene','=',0],
                ];
                $data = $this->getMorningPlate($source,$models,$where,$lg_id,$search,$match_date,$oddsTypeWhere,$ret['type_code'],$ret['game_code']);
                break;
            case 'StStringScene'://串场
                $oddsTypeWhere = [
                    [$models['model_odds'].'.is_stringscene','=',1],
                ];
                if(empty($ret['str_type']) || $ret['str_type'] ==0){//赛事
                    $data = $this->getStringScene($source,$models,$where,$lg_id,$search,'',$oddsTypeWhere);
                }
                if($ret['str_type'] == 1){//参赛表

                }
                if($ret['str_type'] == 2){//冠军盘口
                    $where = $this->commonFunction->getState('StChampion',$model_match,$ret['game_code']);
                    $data = $this->getChampion($source,$models,$where,$lg_id,$search,'StChampion');
                }
                break;
            case 'StChampion'://冠军
                $data = $this->getChampion($source,$models,$where,$lg_id,$search,$ret['type_code']);
                break;
            default:
                throw new \Exception(Render([], '10002', lang('Tips','Sports')->get('PARAM_ERROR')));
        }

        return $data;

    }
    /**
     * 获取各球类 滚球/即将 默认赔率数据
     */
    public function getDefault($data,$game_code,$models,$match_ids,$source,$type_code=''){
        if($game_code == 'zq') {
            //获取滚球下足球默认玩法
            $get_DefaultOdds = require "Config/DefaultOdds.php";
            $DefaultOdds = $get_DefaultOdds['StRollBall']['zq'];
    
            //获取赛事下默认赔率
            $oddsData = ZQoddsModel::getMatchOdds($source, $models,$match_ids,$DefaultOdds);
            foreach ($data as $k=>$v){
                foreach ($v['matchData'] as $kk=>$vv){
                    //获取赛事下赔率并且分组
                    foreach ($oddsData as $kkk=>$vvv) {
                        if($type_code == 'StRollBall'){
                            $vvv['oddsType'] = 'StRollBall';
                        }
                        if ($vv['match_id'] == $vvv['match_id'] and $vvv['sort']==0) {
                            //获取数据源ID
                            $vvv['sourceID'] = $this->commonFunction->getSourceID($vvv['source']);
                            unset($vvv['source']);
                            if($vvv['odds_code'] == $DefaultOdds['zq_concede_guest']){
                                $concede_g = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['zq_concede_home']){
                                $concede_h = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['zq_goal_size_big']){
                                $size_s = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['zq_goal_size_small']){
                                $size_b = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['zq_capot_home']){
                                $capot_h = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['zq_capot_dogfall']){
                                $capot_d = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['zq_capot_guest']){
                                $capot_g = $vvv;
                            }
                        }
                    }
                    $concede_size = [$concede_g,$concede_h,$size_s,$size_b];
                    $capot = [$capot_h,$capot_d,$capot_g];
                    foreach ($concede_size as $key => $vaule){
                        if($vaule == null) unset($concede_size[$key]);
                    }

                    foreach ($capot as $key1 => $vaule1){
                        if($vaule1 == null) unset($capot[$key1]);
                    }
                    sort($concede_size);
                    sort($capot);

                    $data[$k]['matchData'][$kk]['oddsData'] = [$concede_size,$capot];
                }
            }
        }
        if($game_code == 'lq') {
           //获取滚球下篮球默认玩法
            $get_DefaultOdds = require "Config/DefaultOdds.php";
            $DefaultOdds = $get_DefaultOdds['StRollBall']['lq'];
            //获取默认赔率
            $oddsData = LQoddsModel::getMatchOdds($source,$match_ids,$DefaultOdds);
            foreach ($data as $k=>$v){
                foreach ($v['matchData'] as $kk=>$vv){
                    //获取赛事下赔率并且分组
                    $capot = [];
                    $total_size = [];
                    $concede = [];
                    foreach ($oddsData as $kkk=>$vvv) {
                        if($type_code == 'StRollBall'){
                            $vvv['oddsType'] = 'StRollBall';
                        }
                        if ($vv['match_id'] == $vvv['match_id'] and $vvv['sort']==0) {
                            //获取数据源ID
                            $vvv['sourceID'] = $this->commonFunction->getSourceID($vvv['source']);
                            unset($vvv['source']);
                            if($vvv['odds_code'] == $DefaultOdds['lq_concede_home']){
                                $concede_g = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['lq_concede_guest']){
                                $concede_h = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['lq_total_size_big']){
                                $size_s = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['lq_total_size_small']){
                                $size_b = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['lq_capot_home']){
                                $capot_h = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['lq_capot_guest']){
                                $capot_g = $vvv;
                            }
                        }
                    }


                    $concede_size = [$concede_g,$concede_h,$size_s,$size_b];
                    $capot = [$capot_h,$capot_g];
                    foreach ($concede_size as $key => $vaule){
                        if($vaule == null) unset($concede_size[$key]);
                    }

                    foreach ($capot as $key1 => $vaule1){
                        if($vaule1 == null) unset($capot[$key1]);
                    }
                    sort($concede_size);
                    sort($capot);

                    $data[$k]['matchData'][$kk]['oddsData'] = [$concede_size,$capot];
                }
            }
        }
        if($game_code == 'wq') {
            //获取滚球下网球默认玩法
            $get_DefaultOdds = require "Config/DefaultOdds.php";
            $DefaultOdds = $get_DefaultOdds['StRollBall']['wq'];
            //获取网球默认赔率
            $oddsData = WQoddsModel::getMatchOdds($source,$match_ids,$DefaultOdds);
            foreach ($data as $k=>$v){
                foreach ($v['matchData'] as $kk=>$vv){
                    //获取赛事下赔率并且分组
                    $odds = [];
                    foreach ($oddsData as $kkk=>$vvv) {
                        if($type_code == 'StRollBall'){
                            $vvv['oddsType'] = 'StRollBall';
                        }
                        if ($vv['match_id'] == $vvv['match_id'] and $vvv['sort']==0) {
                            //获取数据源ID
                            $vvv['sourceID'] = $this->commonFunction->getSourceID($vvv['source']);
                            unset($vvv['source']);

                            if($vvv['odds_code'] == $DefaultOdds['wq_dishes_home']){
                                $concede_g = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['wq_dishes_guest']){
                                $concede_h = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['wq_kemp_home']){
                                $size_s = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['wq_kemp_guest']){
                                $size_b = $vvv;
                            }
                        }
                    }
                    $concede_size = [$concede_g,$concede_h,$size_s,$size_b];
                    foreach ($concede_size as $key => $vaule){
                        if($vaule == null) unset($concede_size[$key]);
                    }

                    sort($concede_size);
                    $data[$k]['matchData'][$kk]['oddsData'] = $concede_size;
                }
            }
        }
        if($game_code == 'bq') {
            //获取滚球下棒球默认玩法
            $get_DefaultOdds = require "Config/DefaultOdds.php";
            $DefaultOdds = $get_DefaultOdds['StRollBall']['bq'];

            //获取默认赔率
            $oddsData = BQoddsModel::getMatchOdds($source,$match_ids,$DefaultOdds);
            foreach ($data as $k=>$v){
                foreach ($v['matchData'] as $kk=>$vv){
                    //获取赛事下赔率并且分组
                    $odds = [];
                    foreach ($oddsData as $kkk=>$vvv) {
                        if($type_code == 'StRollBall'){
                            $vvv['oddsType'] = 'StRollBall';
                        }
                        if ($vv['match_id'] == $vvv['match_id'] and $vvv['sort']==0) {
                            //获取数据源ID
                            $vvv['sourceID'] = $this->commonFunction->getSourceID($vvv['source']);
                            unset($vvv['source']);
                            if($vvv['odds_code'] == $DefaultOdds['bq_concede_guest']){
                                $concede_g = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['bq_concede_home']){
                                $concede_h = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['bq_total_size_small']){
                                $size_s = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['bq_total_size_big']){
                                $size_b = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['bq_capot_home']){
                                $capot_h = $vvv;
                            }
                            if($vvv['odds_code'] == $DefaultOdds['bq_capot_guest']){
                                $capot_g = $vvv;
                            }
                        }
                    }
                    $concede_size = [$concede_g,$concede_h,$size_s,$size_b];
                    $capot = [$capot_h,$capot_g];
                    foreach ($concede_size as $key => $vaule){
                        if($vaule == null) unset($concede_size[$key]);
                    }
                    foreach ($capot as $key1 => $vaule1){
                        if($vaule1 == null) unset($capot[$key1]);
                    }
                    sort($concede_size);
                    sort($capot);
                    $data[$k]['matchData'][$kk]['oddsData'] = [$concede_size,$capot];
                }
            }
        }

        return $data;
    }
    /**
     * 获取滚球数据
     */
    public function getRollBall($source,$models,$where,$ret,$search=''){
        //获取当前状态下所有联赛
        $leagueData = leagueModel::getRollLeagueData($source,$models,$where,$search);
        if(empty($leagueData)){
            return $leagueData=[];
        }
        //获取联赛id
        $lg_ids = [];
        foreach ($leagueData as $k => $v){
            $lg_ids[] = $v['lg_id'];
        }
        //统计联赛下的赛事及查询赛事
        $matchData = matchModel::getRollMatchDataAll($source,$models,$where,$lg_ids,$ret);

        //如果赛事为空，直接返回
        if(empty($matchData)) return $matchData;

        //===获取当前赛事是否有赔率，如果没有则去除===
        $matchData_new = $this->commonFunction->Handle_Odds_Null($matchData,$models);
        //获取当前match_id
        $match_ids = [];
        foreach($matchData_new as $k=>$v){
            $match_ids[] = $v['match_id'];
        }
        //组装联赛下赛事
        $data = [];
        foreach ($leagueData as $k=>$v){
            $data[$k] = $v;
            foreach ($matchData_new as $kk=>$vv){
                if($v['lg_id'] == $vv['lg_id']){
                    $data[$k]['matchData'][] = $vv;
                }
            }
            $matchNum = count($data[$k]['matchData']);
            $data[$k]['matchNum'] = $matchNum;
        }

        //去除 没有赛事的联赛
        if(!empty($data)){
            foreach($data as $k=>$v){

                if($v['matchNum'] < 1){
                    unset($data[$k]);
                }
            }
            sort($data);
        }
        //获取滚球/即将赛事 默认 赔率数据
        $data = $this->getDefault($data,$ret['game_code'],$models,$match_ids,$source,$ret['type_code']);

        return $data;
    }

    /**
     * 获取即将数据
     */
    public function getSoon($source,$models,$where,$lg_id=0,$ret,$search='',$oddsTypeWhere=''){
        //获取当前状态下所有联赛
        $leagueData = leagueModel::getSoonLeagueData($source,$models,$where,$search);
        if(empty($leagueData)){
            return $leagueData=[];
        }

        //获取联赛id
        $lg_ids = [];
        foreach ($leagueData as $k => $v){
            $lg_ids[] = $v['lg_id'];
        }
        //统计联赛下的赛事及查询赛事
        $matchData = matchModel::getSoonMatchDataAll($source,$models,$where,$lg_ids);

        //如果赛事为空，直接返回
        if(empty($matchData)) return $matchData;

        //===获取当前赛事是否有赔率，如果没有则去除===
        $matchData_new = $this->commonFunction->Handle_Odds_Null($matchData,$models);

        //获取当前match_id
        $match_ids = [];
        foreach($matchData as $k=>$v){
            $match_ids[] = $v['match_id'];
        }
        //获取当前美东时间
        $s_time = strtotime($this->commonFunction->qgmdate('Y-m-d H:i:s', '', -4));
        $data = [];
        foreach ($leagueData as $k=>$v){
            $data[$k] = $v;
            foreach ($matchData_new as $kk=>$vv){
                if($v['lg_id'] == $vv['lg_id']){
                    $wait_time = ceil(((strtotime( $vv['us_time']))-$s_time)/60);
                    $vv['wait_time'] = $wait_time;//追加距离开赛时间
                    $data[$k]['matchData'][] = $vv;
                }
            }

            //获取当前联赛下赛事数量
            $matchNum =  count($data[$k]['matchData']);
            $data[$k]['matchNum'] = $matchNum;
        }

        //去除联赛下没有赛事的联赛
        if(!empty($data)){
            foreach($data as $k=>$v){
                if($v['matchNum'] < 1){
                    unset($data[$k]);
                }
            }
            sort($data);
        }
        //获取滚球/即将赛事 默认 赔率数据
        $data = $this->getDefault($data,$ret['game_code'],$models,$match_ids,$source);

        return $data;
    }

    /**
     * 获取今日数据
     */
    public function getToday($source,$models,$where,$lg_id=0,$search='',$oddsTypeWhere=[]){
        //获取model
        $model_match = $models['model_match'];
        $model_odds = $models['model_odds'];
        $model_league = $models['model_league'];
        $model_result = $models['model_result'];

        //根据联赛id 获取联赛下 赛事赔率数据
        if($lg_id >0){
            $leagueData = $this->getMatchOdds($source,$model_league,$model_match,$model_odds,$where,$search,$lg_id,'',$oddsTypeWhere);
            return $leagueData;
        }

        $data = $this->getMatch($source,$models,$search,$where);
        return $data;
    }

    /**
     * 获取早盘数据
     */
    public function getMorningPlate($source,$models,$where,$lg_id=0,$search='',$time='',$oddsTypeWhere='',$type_code='',$game_code=''){
        //获取model
        $model_match = $models['model_match'];
        $model_odds = $models['model_odds'];
        $model_league = $models['model_league'];
        $model_result = $models['model_result'];

        //根据联赛id 获取联赛下 赛事赔率数据
        if($lg_id >0){
            $leagueData = $this->getMatchOdds($source,$model_league,$model_match,$model_odds,$where,$search,$lg_id,$time,$oddsTypeWhere);
            return $leagueData;
        }

        $data = $this->getMatch($source,$models,$search,$where,$time,'',$type_code,$game_code);
        return $data;
    }

    /**
     * 获取串场数据
     */
    public function getStringScene($source,$models,$where,$lg_id=0,$search='',$time='',$oddsTypeWhere=''){

        //获取model
        $model_match = $models['model_match'];
        $model_odds = $models['model_odds'];
        $model_league = $models['model_league'];
        $model_result = $models['model_result'];

        //根据联赛id 获取联赛下 赛事赔率数据
        if($lg_id >0){
            $leagueData = $this->getMatchOdds($source,$model_league,$model_match,$model_odds,$where,$search,$lg_id,$time,$oddsTypeWhere);
            return $leagueData;
        }

        $data = $this->getMatch($source,$models,$search,$where,$time,'','','',$oddsTypeWhere);
        return $data;
    }

    /**
     * 获取冠军数据
     */
    public function getChampion($source,$models,$where,$lg_id=0,$search='',$type_code=''){

        //获取model
        $model_odds = $models['model_odds'];
        $model_league = $models['model_league'];

        //根据联赛id 获取联赛下 冠军玩法盘口
        if($lg_id >0){
            $last_time = lm($model_league, 'Sports')
                ->select('last_time')
                ->where('id',$lg_id)
                ->first()->last_time;
            $championData = lm($model_odds, 'Sports')
                ->select("id","lg_id","match_id","p_code","odds_code","team","odds","sort","status","odds_only","source")
                ->where('lg_id',$lg_id)
                ->where($where)
                ->where(['status'=>0])
                ->groupBy("id","lg_id","match_id","p_code","odds_code","team","odds","sort","status","odds_only","source")
                ->get()->toArray();
            //按p_code分组
            $p_code=array();
            foreach($championData as $k=>$v){
                //获取数据源ID
                $v['sourceID'] = $this->commonFunction->getSourceID($v['source']);
                unset($v['source']);
                $p_code[$v['p_code']][]=$v;
            }

            $sd = [];
            foreach ($p_code as $k1=>$v1){
                foreach ($v1 as $k2=>$v2){
                    $sd[$v2['p_code']]['last_time'] =$last_time;
                    $sd[$v2['p_code']][$v2['odds_code']][] = $v2;
                }
            }
            return $sd;
        }

        //获取国家/洲下所有联赛及数量
        $data = $this->getMatch($source,$models,$search,$where,'',$type_code);
        return $data;
    }

    /**
     * 获取国家/洲 下联赛
     */
    public function getMatch($source,$models,$search,$where,$time='',$type_code='',$s_type_code='',$game_code='',$oddsTypeWhere=[]){
        //国家下所有联赛
        $country = lm($models['model_league'],"Sports")
            ->leftjoin('st_area_country','st_area_country.id',$models['model_league'].'.country_id')
            ->select('st_area_country.id as country_id','st_area_country.name as region')
            ->distinct('st_area_country.name')
            ->where([[$models['model_league'].'.name_chinese','!=','']])
            ->where($models['model_league'].'.name_chinese','like','%'.$search.'%')
            ->get()
            ->toArray();
        //洲下所有联赛
        $area = lm($models['model_league'],"Sports")
            ->leftjoin('st_area_country','st_area_country.id',$models['model_league'].'.area_id')
            ->select('st_area_country.id as area_id','st_area_country.name as region')
            ->distinct('st_area_country.name')
            ->where([[$models['model_league'].'.country_id','=',0]])
            ->where([[$models['model_league'].'.name_chinese','!=','']])
            ->where($models['model_league'].'.name_chinese','like','%'.$search.'%')
            ->get()
            ->toArray();

        if($type_code != 'StChampion'){//非冠军赛事
            $data = $this->getMatchNum($source,$country,$area,$models,$where,$search,$time,'',$s_type_code,$game_code,$oddsTypeWhere);
        }else{//冠军赛事
            $data = $this->getMatchStChampionNum($source,$country,$area,$models,$where,$search,$time);
        }

        return $data;
    }

    /**
     * 获取联赛下赛事 数量
     * 非冠军盘口
     */
    public function getMatchNum($source,$country,$area,$models,$where,$search,$time='',$type=0,$s_type_code='',$game_code='',$oddsTypeWhere=[]){
        $leagueData = lm($models['model_league'],'Sports')
            ->select('id as lg_id','name_chinese as league','country_id','area_id')
            ->where([[$models['model_league'].'.name_chinese','!=','']])
            ->where($models['model_league'].'.name_chinese','like','%'.$search.'%')
            ->get()
            ->toArray();

        //如果有时间条件 
        $timeWhere = [];
        if(!empty($time)){
            if($time == 'other'){
                $timeWhere[] = ['match_date','>',date("Y-m-d",strtotime("+1weeks",strtotime(date('Y-m-d',time()))))];
            }else{
                $timeWhere[] = ['match_date',$time];
            }
        }
        if($s_type_code == 'StMorningPlate' and $game_code !='zq'){
            $timeWhere[] = ['match_date','>',date('Y-m-d',time())];
        }

        //获取赛事
        $matchData = lm($models['model_match'],'Sports')
            ->select('id as match_id','lg_id')
            ->where($where)
            ->where($timeWhere)
            ->get()
            ->toArray();

        //如果赛事为空，直接返回
        if(empty($matchData)) return $matchData;

        //===获取当前赛事是否有赔率，如果没有则去除===
        $matchData_new = $this->commonFunction->Handle_Odds_Null($matchData,$models,$oddsTypeWhere);

        //按国家
        $countryData = [];
        if(!empty($country) and !empty($leagueData) and !empty($matchData_new)){
            foreach ($country as $k=>$v){
                if($v['country_id']){
                    $countryData[$k] = $v;
                    foreach ($leagueData as $kk=>$vv){
                        if($v['country_id'] == $vv['country_id']){
                            $countryData[$k]['league_count'][] = $vv;
                        }
                    }
                }
            }
        }

        //去除无联赛 国家
        foreach ($countryData as $k=>$v){
            if(count($v) == 2){
                unset($countryData[$k]);
            }
        }

        //按地区
        $areaData = [];
        if(!empty($area) and !empty($leagueData) and($matchData_new)){
            foreach ($area as $k=>$v){
                if($v['area_id']){
                    $areaData[$k] = $v;
                    foreach ($leagueData as $kk=>$vv){
                        if($v['area_id'] == $vv['area_id'] and $vv['country_id'] == 0){
                            $areaData[$k]['league_count'][] = $vv;
                        }
                    }
                }
            }
        }

        //去除无联赛 地区
        foreach ($areaData as $k=>$v){
            if(count($v) == 2){
                unset($areaData[$k]);
            }
        }
        $countryData = $this->commonFunction->array_other_tt($countryData,$matchData_new);
        $areaData = $this->commonFunction->array_other_tt($areaData,$matchData_new);
        $data = array_merge($countryData,$areaData);
        return $data;
    }

    /**
     * 获取联赛下赛事 数量
     * 冠军盘口
     */
    public function getMatchStChampionNum($source,$country,$area,$models,$where,$search,$time='',$type=0){

        $leagueData = lm($models['model_league'],'Sports')
            ->select('id as lg_id','name_chinese as league','country_id','area_id')
            ->where([[$models['model_league'].'.name_chinese','!=','']])
            ->where($models['model_league'].'.name_chinese','like','%'.$search.'%')
            ->get()
            ->toArray();

        $oddsData = lm($models['model_odds'],'Sports')
            ->select('id','lg_id','p_code')
            ->distinct("p_code")//去重
            ->where($where)
            ->where(['status'=>0])
            ->get()
            ->toArray();

        //按国家
        $countryData = [];
        if(!empty($country) and !empty($leagueData) and !empty($oddsData)){
            foreach ($country as $k=>$v){
                if($v['country_id']){
                    $countryData[$k] = $v;
                    foreach ($leagueData as $kk=>$vv){
                        if($v['country_id'] == $vv['country_id']){
                            $countryData[$k]['league_count'][] = $vv;
                        }
                    }
                }
            }
        }
        //去除无联赛 国家
        foreach ($countryData as $k=>$v){
            if(count($v) == 2){
                unset($countryData[$k]);
            }
        }

        //按地区
        $areaData = [];
        if(!empty($area) and !empty($leagueData) and($oddsData)){
            foreach ($area as $k=>$v){
                if($v['area_id']){
                    $areaData[$k] = $v;
                    foreach ($leagueData as $kk=>$vv){
                        if($v['area_id'] == $vv['area_id'] and $vv['country_id'] == 0){
                            $areaData[$k]['league_count'][] = $vv;
                        }
                    }
                }
            }
        }

        //去除无联赛 地区
        foreach ($areaData as $k=>$v){
            if(count($v) == 2){
                unset($areaData[$k]);
            }
        }


        $countryData = $this->commonFunction->array_gj_tt($countryData,$oddsData);
        $areaData = $this->commonFunction->array_gj_tt($areaData,$oddsData);
        $data = array_merge($countryData,$areaData);
        return $data;
    }

    /**
     * 获取联赛下 赛事赔率
     */
    public function getMatchOdds($source,$model_league,$model_match,$model_odds,$where,$search,$lg_id,$time='',$oddsTypeWhere=[]){        
        $leagueData = lm($model_league,"Sports")
            ->select('id as lg_id','name_chinese as leagueName')
            ->where('id',$lg_id)
            ->first();
        //根据时间 拼装查询条件
        $whereTime = [];
        if(!empty($time)){
            if($time == 'other'){
                //其他时间（七天后）
                $whereTime = [
                    ['match_date','>',date("Y-m-d",strtotime("+1weeks",strtotime(date('Y-m-d',time()))))],
                ];
            }elseif($time == date('Y-m-d')){
                //今天
                $whereTime = [
                    ['is_morningplate','=',1],
                    ['match_date','=',$time],
                    ['match_time','>',date("H:i:s", time())]
                ];

            }else{
                //今天以后 七天内
                $whereTime = [
                    ['match_date','=',$time]
                ];
            }
        }

        $matchData = lm($model_match,"Sports")
            ->select($model_match.'.id as match_id',$model_match.'.tag','match_date',$model_match.'.match_time',$model_match.'.home_team',$model_match.'.guest_team')
            ->where($model_match.'.lg_id',$lg_id)
            ->where($where)
            ->where($whereTime)
            ->where(function($query)use ($model_match,$search){
                $query->where($model_match.'.home_team','like','%'.$search.'%')
                    ->orWhere(function($query)use ($model_match,$search) {
                        $query->where($model_match . '.guest_team', 'like', '%' . $search . '%');
                    });
            })
            ->get()
            ->toarray();

        //如果赛事为空，直接返回
        if(empty($matchData)) return $matchData;

        //===获取当前赛事是否有赔率，如果没有则去除===
        $models = ['model_odds'=>$model_odds];
        $matchData_new = $this->commonFunction->Handle_Odds_Null($matchData,$models,$oddsTypeWhere);

        //获取各球类默认赔率
        $game_code = $_REQUEST['game_code'];
        switch ($game_code) {
            case 'zq'://足球
                $matchData = $this->getOddsData->getOddsZQ($matchData_new, $model_odds, $source,$oddsTypeWhere);
                break;
            case 'lq'://篮球
                $matchData = $this->getOddsData->getOddsLQ($matchData_new, $model_odds, $source,$oddsTypeWhere);
                break;
            case 'wq'://网球
                $matchData = $this->getOddsData->getOddsWQ($matchData_new, $model_odds, $source,$oddsTypeWhere);
                break;
            case 'bq'://棒球
                $matchData = $this->getOddsData->getOddsBQ($matchData_new, $model_odds, $source,$oddsTypeWhere);
                break;
        }
        $leagueData->matchNum = count($matchData);
        $leagueData->matchData = $matchData;

        return $leagueData;

    }

    /**
     * @param $source 数据源
     * @param $where 该状态 查询条件
     * @return array
     * @throws \Exception
     * 获取所有即将开赛 数据
     */
    public function getAllSoon($source,$where){
        $game = lm('GameType', 'Sports')->select('id','game_name','game_code','game_ico_url')->where('status',1)->get()->toArray();
        //获取当前美东时间
        $s_time = strtotime($this->commonFunction->qgmdate('Y-m-d H:i:s', '', -4));
        $data=[];
        foreach ($game as $key=>$item){
            if($item['game_code'] !='gj'){
                $model = $this->commonFunction->getModels($item['game_code']);

                $matchData = lm($model['model_match'], 'Sports')
                    ->select('id as match_id','home_team','guest_team','match_time','us_time')
                    ->where($where)
                    ->orderBy('match_time','asc')
                    ->get()->toArray();
                //===获取当前赛事是否有赔率，如果没有则去除===
                $matchData = $this->commonFunction->Handle_Odds_Null($matchData,$model);
                $matchNum = count($matchData);

                $matchData = array_slice($matchData,0,6);
                foreach ($matchData as $key1 => $item1){
                    //获取等待时间
                    $wait_time = ceil(((strtotime($item1['us_time']))-$s_time)/60);
                    $matchData[$key1]['wait_time'] = $wait_time;
                }

                if($matchNum > 0){
                    $data[$item['game_code']]['matchData'] = $matchData;
                    $data[$item['game_code']]['matchNum'] = $matchNum;
                    $data[$item['game_code']]['gameName'] = $item['game_name'];
                    $data[$item['game_code']]['gameCode'] = $item['game_code'];

                }
            }
        }

        return $data;
    }

    /**
     * 获取欧冠  各状态赛事数据
     */
    public function getUEFAChampions($source){
        //根据搜索查询
        if(!empty($_GET['search'])){
            $search = $_GET['search'];
        }
        $model = $this->commonFunction->getModels('gj',1);

        $model_league = $model['model_league'];
        $leagueData = lm($model_league,'Sports')
            ->select('name_chinese','id as lg_id','last_time')
            ->where($model_league.'.name_chinese','欧洲冠军杯')
            ->first();
        //获取滚球数据
        $StRollBall = $this->getUEFAStRollBall($model,'StRollBall',$source,$leagueData->lg_id,$search);
        //获取今日数据
        $StToday = $this->getUEFAStToday($model,'StToday',$source,$leagueData->lg_id,$search);
        //获取早盘数据
        $StMorningPlate = $this->getUEFAStMorningPlate($model,'StMorningPlate',$source,$leagueData->lg_id,$search);
        //获取冠军盘口数据
        $StChampion = $this->getUEFAStChampion($model,'StChampion',$source,$leagueData->lg_id,$leagueData->last_time);

        $data = [
            'lg_id' => $leagueData->lg_id,
            'leagueName'=> $leagueData->name_chinese,
            'StRollBall'=>[//滚球数据
                'typeName'=>'滚球',
                'matchNum'=>count($StRollBall),
                'matchData'=>$StRollBall
            ],
            'StToday'=>[//今日数据
                'typeName'=>'今日',
                'matchNum'=>count($StToday),
                'matchData'=>$StToday
            ],
            'StMorningPlate'=>[//早盘数据
                'typeName'=>'早盘',
                'matchNum'=>count($StMorningPlate),
                'matchData'=>$StMorningPlate
            ],
            'StChampion'=>[//冠军盘口
                'typeName'=>'冠军盘口',
                'matchNum'=>count($StChampion),
                'matchData'=>$StChampion
            ]
        ];

        return $data;
    }

    /**
     * 获取欧冠 滚球数据
     */
    public function getUEFAStRollBall($model,$type_code,$source,$lg_id,$search=''){
        $model_match = $model['model_match'];
        $model_odds = $model['model_odds'];
        $model_result = $model['model_result'];

        $where = $this->commonFunction->getState($type_code,$model_match,'zq');
        $matchData = lm($model_match,"Sports")
            ->leftjoin($model_result,$model_result.'.match_id',$model_match.'.id')
            ->select($model_match.'.id as match_id',$model_match.'.tag','match_date',$model_match.'.match_time',$model_match.'.home_team',$model_match.'.guest_team','home_score','guest_score',$model_result.'.match_time as a_time','match_process')
            ->where($model_match.'.lg_id',$lg_id)
            ->where($where)
            ->where(function($query)use ($model_match,$search){
                $query->where($model_match.'.home_team','like','%'.$search.'%')
                    ->orWhere(function($query)use ($model_match,$search) {
                        $query->where($model_match . '.guest_team', 'like', '%' . $search . '%');
                    });
            })
            ->get()
            ->toarray();

        //获取赛事id
        $match_ids = [];
        foreach ($matchData as $k => $v){
            $match_ids[] = $v['match_id'];
        }
        //获取赛事下滚球默认赔率
        $oddsData = ZQoddsModel::getMatchOdds($source,$model,$match_ids);
        foreach ($matchData as $k=>$v){
            //获取赛事下赔率并且分组
            $capot = [];
            $concede_size = [];
            foreach ($oddsData as $kk=>$vv){
                if ($vv['match_id'] == $v['match_id'] and $vv['sort']==0) {
                    if($vv['p_code'] == 'concede_size'){
                        $concede_size[] = $vv;
                    }
                    if($vv['p_code'] == 'capot'){
                        $capot[] = $vv;
                    }
                }
            }
            $matchData[$k]['oddsData'] = [$concede_size,$capot];
        }
        return $matchData;
    }

    /**
     * 获取欧冠 今日数据
     */
    public function getUEFAStToday($model,$type_code,$source,$lg_id,$search=''){
        $model_match = $model['model_match'];
        $model_odds = $model['model_odds'];

        $where = $this->commonFunction->getState($type_code,'','zq');
        $matchData = lm($model_match,'Sports')
            ->select('id as match_id','match_date','match_time','tag','home_team','guest_team')
            ->where($where)
            ->where('lg_id',$lg_id)
            ->where(function($query)use ($model_match,$search){
                $query->where($model_match.'.home_team','like','%'.$search.'%')
                    ->orWhere(function($query)use ($model_match,$search) {
                        $query->where($model_match . '.guest_team', 'like', '%' . $search . '%');
                    });
            })
            ->get()->toArray();

        //获取赛事id
        $match_ids = [];
        foreach ($matchData as $k => $v){
            $match_ids[] = $v['match_id'];
        }
        //获取赔率数据
        $oddsData = lm($model_odds, "Sports")
            ->select( 'id','p_code', 'odds_code','odds_only','status', 'odds', 'condition', 'sort','match_id','source')
            ->whereIn('match_id', $match_ids)
            ->where(['status'=>0])
            ->groupBy($model_odds . '.id','p_code', 'odds_code','odds_only', $model_odds . '.status', 'odds', 'condition', 'sort','match_id','source')
            ->orderBy($model_odds . '.id','desc')
            ->get()
            ->toarray();
        foreach ($matchData as $k=>$v){
            foreach ($oddsData as $kk=>$vv){
                if($v['match_id'] == $vv['match_id']){
                    //获取数据源ID
                    $vv['sourceID'] = $this->commonFunction->getSourceID($vv['source']);
                    unset($vv['source']);
                    $matchData[$k]['oddsData'][] = $vv;
                }
            }
        }
        return $matchData;
    }

    /**
     * 获取欧冠 早盘数据
     */
    public function getUEFAStMorningPlate($model,$type_code,$source,$lg_id,$search=''){
        $model_match = $model['model_match'];
        $model_odds = $model['model_odds'];

        $where = $this->commonFunction->getState($type_code,'','zq');

        $matchData = lm($model_match,'Sports')
            ->select('id as match_id','match_date','match_time','tag','home_team','guest_team')
            ->where($where)
            ->where('lg_id',$lg_id)
            ->where(function($query)use ($model_match,$search){
                $query->where($model_match.'.home_team','like','%'.$search.'%')
                    ->orWhere(function($query)use ($model_match,$search) {
                        $query->where($model_match . '.guest_team', 'like', '%' . $search . '%');
                    });
            })
            ->get()->toArray();

        $data = $this->getOddsData->getOddsZQ($matchData,$model_odds,$source,[]);

        return $data;
    }

    /**
     * 获取 欧冠 冠军盘口数据
     */
    public function getUEFAStChampion($model,$type_code,$source,$lg_id,$last_time=''){
        $model_odds = $model['model_odds'];

        $where = $this->commonFunction->getState($type_code,'','zq');
        $championData = lm($model_odds, 'Sports')
            ->select("id","lg_id","match_id","p_code","odds_code","team","odds","sort","status","odds_only","source")
            ->where('lg_id',$lg_id)
            ->where($where)
            ->where(['status'=>0])
            ->groupBy("id","lg_id","match_id","p_code","odds_code","team","odds","sort","status","odds_only","source")
            ->get()->toArray();

        //按p_code分组
        $p_code=array();
        foreach($championData as $k=>$v){
            //获取数据源ID
            $v['sourceID'] = $this->commonFunction->getSourceID($v['source']);
            unset($v['source']);
            $p_code[$v['p_code']][]=$v;
        }

        $data = [];
        foreach ($p_code as $k1=>$v1){
            foreach ($v1 as $k2=>$v2){
                $data[$v2['p_code']]['last_time'] =$last_time;
                $data[$v2['p_code']][$v2['odds_code']][] = $v2;
            }
        }
        return $data;
    }

}