<?php
/**
 * Created by PhpStorm.
 * User: Jun.peng
 * Date: 2019/5/14
 * Time: 16:25
 */
namespace App\Sports\Controller;

use BaseController\Controller;
use Biz\Match\GetmatchData;
use Biz\Match\GetOddsData;
use App\Sports\Model\St_area as areaModel;
use App\Sports\Model\St_country as countryModel;
use App\Sports\Model\St_zq_odds as ZQoddsModel;

/**
 * Class MatchListWeb
 * @package App\Sports\Controller
 * pc端 接口
 */
class MatchListWeb extends Controller{
    private $getTypeData;
    public function init() {
        $this->getTypeData = new GetmatchData();
        $this->getOddsData = new GetOddsData();
        $this->commonFunction =  C()->get('commonFunction');
    }

    //各球类玩法列表及数量
    public function gameList(){

        $type = $_REQUEST['type'];//状态代码
        $game_code = $_REQUEST['game_code'];//球类代码
        $p_code = $_REQUEST['p_code'];//父级玩法代码
        $time = $_REQUEST['match_date'];//时间条件

        try {
            if(empty($type) ){
                throw new \Exception(Render([], '10001', lang('Tips','Sports')->get('PARAM_ERROR')));
            }
            switch ($type){
                case 'StRollBall'://滚球
                    $this->getRollBall($type,$game_code,$p_code);
                    break;
                case 'StSoon'://即将
                    $this->Other($type,$game_code,$p_code,$time);
                    break;
                case 'StToday'://今日
                    $this->Other($type,$game_code,$p_code,$time);
                    break;
                case 'StMorningPlate'://早盘
                    $this->Other($type,$game_code,$p_code,$time);
                    break;
                case 'StStringScene'://串场
                    $this->Other($type,$game_code,$p_code,$time);
                    break;
                default:
                    throw new \Exception(Render([], '10002', lang('Tips','Sports')->get('PARAM_ERROR')));
            }
            Render([], '1', lang('Tips','Sports')->get('success'));
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    //获取滚球
    public function getRollBall($type,$game_code,$p_code){
        //根据球类代码及玩法代码 获取相关赛事赔率数据
        if(!empty($game_code)){
            $matchData = $this->getMatchData($type,$game_code,$p_code);

            Render($matchData, '1', lang('Tips','Sports')->get('success'));
        }

        $game = lm('GameType', 'Sports')->select('game_code')->where('status',1)->get()->toArray();
        $gameData = [];
        foreach ($game as $k=>$v){
            if($v['game_code'] !='gj'){
                $models = $this->commonFunction->getModels($v['game_code'],1);
                $where = $this->commonFunction->getState($type,$models['model_match']);
                $matchNum = lm($models['model_league'],"Sports")
                    ->join($models['model_match'],$models['model_match'].'.lg_id',$models['model_league'].'.lg_id')
                    ->where($models['model_match'].'.source',$this->source['source'])
                    ->where($where)
                    ->count("*");
                //获取满足状态的球类
                if($matchNum != 0){
                    $gameData[$k]['game_code'] = $v['game_code'];
                    $gameData[$k]['game_num'] = $matchNum;
                }
            }
        }
        sort($gameData);
        $num = [];
        foreach ($gameData as $kk=>$vv){
            $num[] =  $vv['game_num'];
        }
        $gameData[]['all_num'] = array_sum($num);

        Render($gameData, '1', lang('Tips','Sports')->get('success'));
    }
    //获取非滚球数据
    public function Other($type,$game_code,$p_code,$time=''){
        //根据球类代码及玩法代码 获取相关赛事赔率数据
        if(!empty($game_code) and !empty($p_code)){
            $matchData = $this->getMatchData($type,$game_code,$p_code,$time);

            Render($matchData, '1', lang('Tips','Sports')->get('success'));
        }
        //根据状态获取所有球类/玩法下赛事数量
        $game = lm('GameType', 'Sports')->select('game_code')->where('status',1)->get()->toArray();
        $oddsCodeNum = [];
        foreach ($game as $k=>$v) {
            if ($v['game_code'] != 'gj') {
                //获取各球类下父级玩法赛事数量
                $oddsCodeNum[$k] = $this->getMatchData($type,$v['game_code'],'');
            }
        }

        $matchDataNum = [];
        foreach ($oddsCodeNum as $k => $v){
            foreach ($v as $kk=>$vv){
                $matchDataNum[] = $vv;
            }
        }
        Render($matchDataNum, '1', lang('Tips','Sports')->get('success'));
    }

    //获取赛事数据
    public function getMatchData($type,$game_code,$p_code='',$time=''){
        //$p_code 获取具体玩法下的赛事数据
        $models = $this->commonFunction->getModels($game_code,1);
        $where = $this->commonFunction->getState($type,$models['model_match']);

        $select = [$models['model_match'].'.match_id'];
        $timeWhere = [];
        //如果有传玩法代码，则获取查询字段
        if($p_code){
            //时间条件
            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($p_code == 'kemp'){
                $select = [$models['model_league'].'.lg_id',$models['model_league'].'.name_chinese as leagueName','last_time','country_id','area_id'];
            }else{
                $select = [$models['model_league'].'.lg_id',$models['model_league'].'.name_chinese as leagueName',$models['model_match'].'.match_id','home_team','guest_team','match_date','match_time','tag','country_id','area_id'];
            }
        }
        //如果是滚球
        if($type == 'StRollBall'){
            $select = [$models['model_league'].'.lg_id',$models['model_league'].'.name_chinese as leagueName',$models['model_match'].'.match_id','home_team','guest_team','match_date','match_time','tag','country_id','area_id'];
        }
        //赛事数据
        $matchNum = lm($models['model_league'],"Sports")
            ->join($models['model_match'],$models['model_match'].'.lg_id',$models['model_league'].'.lg_id')
            ->select($select)
            ->where($models['model_match'].'.source',$this->source['source'])
            ->where($where)
            ->where($timeWhere)
            ->get()->toArray();

        //赔率数据
        $oddsCodeNum = $this->getOddsData($game_code,$models['model_odds'],$matchNum,$p_code,$type);
        if($p_code){
            $match_odds = [];
            if($p_code == 'kemp'){
                $matchNum = $this->uniquArr($matchNum,'lg_id');

                foreach ($oddsCodeNum as $k=>$v){
                    foreach ($matchNum as $kk => $vv){
                        if($v['lg_id'] == $vv['lg_id']){
                            $match_odds[$kk]['area_id'] = $vv['area_id'];
                            $match_odds[$kk]['country_id'] = $vv['country_id'];
                            $match_odds[$kk]['lg_id'] = $vv['lg_id'];
                            $match_odds[$kk]['leagueName'] = $vv['leagueName'];
                            $match_odds[$kk]['last_time'] = $vv['last_time'];
                            $match_odds[$kk]['oddsData'][] = $v;
                        }
                    }

                }
                sort($match_odds);

                $gjData = [];
                foreach ($match_odds as $k=>$v){
                    //按p_code分组
                    $p_code=array();
                    foreach($v['oddsData'] as $kk=>$vv){
                        $p_code[$vv['p_code']][]=$vv;
                    }

                    $sd = [];
                    foreach ($p_code as $k1=>$v1){
                        foreach ($v1 as $k2=>$v2){
                            $sd[$v2['p_code']]['last_time'] =$v['last_time'];
                            $sd[$v2['p_code']][$v2['odds_code']][] = $v2;
                        }
                    }
                    $gjData[] = $sd;
                }
                //国家数据
                $country = countryModel::getName();
                //获取国家联赛列表
                $countryList = [];
                foreach ($country as $k=>$v){
                    foreach ($match_odds as $kk=>$vv){
                        if($v['country_id'] == $vv['country_id']){
                            unset($vv['last_time']);
                            //联赛下父级玩法 盘口数量
                            $oddsCode = array_column($vv['oddsData'], 'odds_code');
                            //获取冠军盘口下 父级玩法 数量
                            $oddsCodeN = array_count_values($oddsCode);
                            $vv['matchNum'] = count($oddsCodeN);
                            unset($vv['oddsData']);
                            $v['lg_list'][] = $vv;
                            $countryList[$k] = $v;
                        }
                    }
                }
                sort($countryList);

                //地区数据
                $area = areaModel::getName();
                //获取地区联赛列表
                $areaList = [];
                foreach ($area as $k=>$v){
                    foreach ($match_odds as $kk=>$vv){
                        if($v['id'] == $vv['area_id']){
                            unset($vv['last_time']);
                            //联赛下父级玩法 盘口数量
                            $oddsCode = array_column($vv['oddsData'], 'odds_code');
                            //获取冠军盘口下 父级玩法 数量
                            $oddsCodeN = array_count_values($oddsCode);
                            $vv['matchNum'] = count($oddsCodeN);
                            unset($vv['oddsData']);
                            $v['lg_list'][] = $vv;
                            $areaList[$k] = $v;
                        }
                    }
                }
                sort($areaList);
                //国家/地区 联赛列表
                $leagueList = array_merge($countryList,$areaList);
                $data = [$gjData,$leagueList];
                return $data;
            }
            foreach ($oddsCodeNum as $k=>$v){
                foreach ($matchNum as $kk=>$vv){
                    if($v['match_id'] == $vv['match_id']){
                        $match_odds[$kk]['lg_id'] = $vv['lg_id'];
                        $match_odds[$kk]['leagueName'] = $vv['leagueName'];
                        $match_odds[$kk]['match_id'] = $vv['match_id'];
                        $match_odds[$kk]['home_team'] = $vv['home_team'];
                        $match_odds[$kk]['guest_team'] = $vv['guest_team'];
                        $match_odds[$kk]['match_date'] = $vv['match_date'];
                        $match_odds[$kk]['match_time'] = $vv['match_time'];
                        $match_odds[$kk]['tag'] = $vv['tag'];
                        $match_odds[$kk]['oddsData'][] = $v;
                    }
                }
            }
            //排序
            sort($match_odds);
            $data = [];
            foreach ($matchNum as $k=>$v){
                foreach ($match_odds as $kk=>$vv){
                    if($v['lg_id'] == $vv['lg_id']){
                        $data[$k]['area_id'] = $v['area_id'];
                        $data[$k]['country_id'] = $v['country_id'];
                        $data[$k]['lg_id'] = $v['lg_id'];
                        $data[$k]['leagueName'] = $v['leagueName'];
                        $data[$k]['matchData'][] = $vv;
                    }
                }
            }
            //赛事详细数据 去重
            $matchData = $this->uniquArr($data,'lg_id');

            //国家数据
            $country = countryModel::getName();
            //获取国家联赛列表
            $countryList = [];
            foreach ($country as $k=>$v){
                foreach ($matchData as $kk=>$vv){
                    if($v['country_id'] == $vv['country_id']){
                        //联赛下赛事数量
                        $vv['matchNum'] = count($vv['matchData']);
                        unset($vv['matchData']);
                        $v['lg_list'][] = $vv;
                        $countryList[$k] = $v;
                    }
                }
            }
            sort($countryList);

            //地区数据
            $area = areaModel::getName();
            //获取地区联赛列表
            $areaList = [];
            foreach ($area as $k=>$v){
                foreach ($matchData as $kk=>$vv){
                    if($v['id'] == $vv['area_id']){
                        //联赛下赛事数量
                        $vv['matchNum'] = count($vv['matchData']);
                        unset($vv['matchData']);
                        $v['lg_list'][] = $vv;
                        $areaList[$k] = $v;
                    }
                }
            }
            sort($areaList);

            //国家/地区 联赛列表
            $leagueList = array_merge($countryList,$areaList);
            $data = [$matchData,$leagueList];
            return $data;
        }
        return $oddsCodeNum;
    }
    //根据match_id获取赔率数据
    public function getOddsData($game_code,$model_odds,$match_ids,$p_code='',$type=''){
        $match_id = [];
        $lg_ids = [];
        foreach ($match_ids as $k => $v){
           $match_id[] = $v['match_id'];
           $lg_ids[] = $v['lg_id'];
        }
        $select = ['match_id','p_code'];
        $whereOr = [];
        //有父级玩法，则获取该玩法下详细数据
        if($p_code){
            $select = ['lg_id','match_id','id','p_code','odds_code','condition','odds','odds_only','sort','status','team'];
            //获取冠军盘口
            if($p_code == 'kemp'){
                $whereOr = [['sort','=',0],['type','=',1]];
                $oddsData = lm($model_odds,"Sports")
                    ->select($select)
                    ->whereIn('lg_id', $lg_ids)
                    ->where('source',$this->source['source'])
                    ->where($whereOr)
                    ->get()
                    ->toArray();
                return $oddsData;
            }
            if($p_code == 'concede' and $game_code == 'zq'){
                $whereOr = [['sort','=',0]];
                $oddsData = lm($model_odds,"Sports")
                    ->select($select)
                    ->whereIn('match_id', $match_id)
                    ->where('source',$this->source['source'])
                    ->where($whereOr)
                    ->whereIn('p_code',['concede','goal_size'])
                    ->get()
                    ->toArray();
                return $oddsData;
            }
            if($p_code == 'concede'  and $game_code == 'lq'){
                $whereOr = [['sort','=',0]];
                $oddsData = lm($model_odds,"Sports")
                    ->select($select)
                    ->whereIn('match_id', $match_id)
                    ->where('source',$this->source['source'])
                    ->where($whereOr)
                    ->whereIn('p_code',['concede','total_size','team_score'])
                    ->get()
                    ->toArray();
                return $oddsData;
            }
            if($p_code == 'concede'  and $game_code == 'wq'){
                $whereOr = [['sort','=',0]];
                $oddsData = lm($model_odds,"Sports")
                    ->select($select)
                    ->whereIn('match_id', $match_id)
                    ->where('source',$this->source['source'])
                    ->where($whereOr)
                    ->whereIn('p_code',['dishes','bureau','total_number'])
                    ->get()
                    ->toArray();
                return $oddsData;
            }
            if($p_code == 'concede'  and $game_code == 'bq'){
                $whereOr = [['sort','=',0]];
                $oddsData = lm($model_odds,"Sports")
                    ->select($select)
                    ->whereIn('match_id', $match_id)
                    ->where('source',$this->source['source'])
                    ->where($whereOr)
                    ->whereIn('p_code',['concede','total_size','two_sides'])
                    ->get()
                    ->toArray();
                return $oddsData;
            }
            else{
                $whereOr = [['p_code','=',$p_code],['sort','=',0]];
                $oddsData = lm($model_odds,"Sports")
                    ->select($select)
                    ->whereIn('match_id', $match_id)
                    ->where('source',$this->source['source'])
                    ->where($whereOr)
                    ->get()
                    ->toArray();
                return $oddsData;
            }
        }
        //如果是滚球，则获取滚球下详细数据
        if($type == 'StRollBall'){
            $select = ['lg_id','match_id','id','p_code','odds_code','condition','odds','odds_only','sort','status','team'];
            $whereOr = [['sort','=',0]];
            //获取滚球下，各球类默认玩法代码
            if($game_code == 'zq'){
                $p_code = ['concede','goal_size'];
            }
            if($game_code == 'lq'){
                $p_code = ['concede','total_size','team_score'];
            }
            if($game_code == 'wq'){
                $p_code = ['dishes','bureau','total_number'];
            }
            if($game_code == 'bq'){
                $p_code = ['concede','total_size','two_sides'];
            }
            $oddsData = ZQoddsModel::getOddsDataPC($model_odds,$select,$match_id,$whereOr,$p_code);
            return $oddsData;
        }
        $oddsData = lm($model_odds,"Sports")
            ->select($select)
            ->whereIn('match_id', $match_id)
            ->where('source',$this->source['source'])
            ->where($whereOr)
            ->get()
            ->toArray();

        //按父级玩法分组
        $oddsCode = [];
        foreach ($oddsData as $kk=>$vv){
           $oddsCode[$vv['p_code']][]= $vv;
        }

        // 去重 获取每个玩法下的赛事数量
        $oddsCodeNum = [];
        $game_num = count($match_ids);
        foreach ($oddsCode as $kkk=>$vvv){
            $oddsCodeNum[$kkk]['game_code'] = $game_code;
            $oddsCodeNum[$kkk]['game_num'] = $game_num;
            $oddsCodeNum[$kkk]['p_code'] = $kkk;
            $oddsCodeNum[$kkk]['code_num'] = count($this->uniquArr($vvv,'match_id'));
        }

        sort($oddsCodeNum);
        return $oddsCodeNum;
    }

    /**
     * 二维数组根据某个字段去重
     * @param array $array  二维数组
     * @para array  去重后的数组
     */
     function uniquArr($array,$key){
        $result = array();
        foreach($array as $k=>$val){
            $code = false;
            foreach($result as $_val){
                if($_val[$key] == $val[$key]){
                    $code = true;
                    break;
                }
            }
            if(!$code){
                $result[]=$val;
            }
        }
        return $result;
    }

    //获取直播数据
    public function getBroadcast(){
         $data = lm('st_broadcast',"Sports")
             ->select('id','showid','shower','league_name','game_type','host_team','guest_team','start_time','doing')
             ->get()
             ->toArray();

        Render($data, '1', lang('Tips','Sports')->get('success'));
    }
}