<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request as Req;
use Illuminate\Support\Facades\DB;
Use App\Lib\Settlement\SettlementWinFail;
use App\Models;
use Request;

/**
 *
 */
class SportsBasketController extends Controller {

	public function score(Req $req) {
		$request['name_chinese'] = isset($req->name_chinese) ? trim($req->name_chinese) : '-1';
		$request['home_team'] = isset($req->home_team) ? trim($req->home_team) : null;
		$request['match_date'] = isset($req->match_date) ? trim($req->match_date) : null;
		$request['recommend'] = isset($req->recommend) ? trim($req->recommend) : '';
		$request['status'] = isset($req->status) ? trim($req->status) : '-1';
		$request['sureblurs'] = isset($req->sureblurs) ? $req->sureblurs : 'on';

//        $source = \App\Models\Setinfo::where('id','1000')->first();
//        if($source->infocontent != '混合数据'){
//            $data = \App\Models\BasketLeague::join('st_lq_local_league','st_lq_league.id','=','st_lq_local_league.lg_id')->select('st_lq_league.id','st_lq_league.name_chinese')->where('st_lq_local_league.source',$source->infocontent)->get();
//        }else{
//            $data = \App\Models\BasketLeague::select('id','name_chinese')->get();
//        }

		$data = \App\Models\BasketLeague::select('id','lg_id','name_chinese')->get();
		$request['league'] = $data;
		$dt = \App\Lib\DataTable\DataTable::init();
		$dt->setDataSource('/admin/SportsBasket/info');
		$dt->setLang('sportsbase');
		$dt->addColsFields('match_id', array('templet' => '#userdetail', 'sort' => true, 'width' => 100));
		$dt->addColsFields('lg_id', array('templet' => '#userdetail', 'sort' => true, 'width' => 100));
		$dt->addColsFields('name_chinese', array('templet' => '#userdetail', 'sort' => false, 'width' => 200));
		$dt->addColsFields('home_guest', array('templet' => '#userdetail', 'sort' => false, 'width' => 260));
		$dt->addColsFields('match_date', array('templet' => '#userdetail', 'sort' => true, 'width' => 120));
		$dt->addColsFields('match_time', array('templet' => '#userdetail', 'sort' => true, 'width' => 100));
		$dt->addColsFields('recommend', array('templet' => '#recommend', 'sort' => false, 'width' => 120,'align' => 'center'));
		$dt->addColsFields('status', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
		//$dt->addColsFields('result', array( 'sort' => false, 'width' => 100));
		//$arr[] = 'view';
		if (checkRriv('/admin/SportsBasket/edit')) {
			$arr[] = 'edit';
		}
		if (checkRriv('/admin/SportsBasket/odds')) {
			$arr[] = 'odds';
		}
		$dt->setToolBar($arr, array('width' => 200));
		$dt->enableCheckBox();
		return view('sports/basket_match', $dt->render($request));
	}

	function info(Req $req) {
		$page = Request::has('page') ? Request::get('page') : '';
		$list = Request::has('limit') ? Request::get('limit') : 10;
		$name_chinese = Request::has('name_chinese') ? Request::get('name_chinese') : '';
		$home_team = Request::has('home_team') ? Request::get('home_team') : '';
		$match_date = Request::has('match_date') ? Request::get('match_date') : '';
		//$match_date = $req->input('match_date');
//        if(!empty($match_date)){
//            return 2;
//        }
		$status = Request::has('status') ? Request::get('status') : '';
		$sureblur = Request::has('sureblurs') ? Request::get('sureblurs') : 'off';
		$where = array();
		$orwhere = array();
		if (!empty($name_chinese) && $name_chinese!=-1) {
			$where[] = array('st_lq_league.name_chinese', '=', $name_chinese);
		}
		if (!empty($home_team)) {
			if (empty($sureblur) || $sureblur == 'off') {
				$where[] = array('st_lq_competition.home_team', 'like', '%' . $home_team . '%');
				$orwhere[] = array('st_lq_competition.guest_team', 'like', '%' . $home_team . '%');
			} else {
				$where[] = array('st_lq_competition.home_team', '=', $home_team);
				$orwhere[] = array('st_lq_competition.guest_team', '=', $home_team);
			}
		}
		if (!empty($match_date)) {
			$where[] = array('st_lq_competition.match_date', '=', $match_date);
		}
		if ($status != -1) {
			$where[] = array('st_lq_competition.status', '=', $status);
		}

		$newapp = new \App\Models\SportsBasket();
		$data = $newapp->getinfo($list, $page, $where,$orwhere);
		return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total']);
	}
	/**
	 *设置是否为推荐赛事
	 */
	function recommendmatch(Req $req) {
		$id = $req->id;
		$recommend = is_numeric($req->recommend) ? intval($req->recommend) : '';
		if (empty($id) || !is_numeric($recommend)) {
			return responseToJson(-2020100102);
		}
		$u_db = new \App\Models\SportsBasket;
		$data = array(
			'recommend' => $recommend,
		);
		$res = $u_db->updateInfos($data, $id);
		return responseToJson($res);
	}
	/**
	 *获取所有篮球联赛信息
	 */
	function getParent() {

//        $source = \App\Models\Setinfo::where('id','1000')->first();
//        if($source->infocontent != '混合数据'){
//            $data = \App\Models\BasketLeague::join('st_lq_local_league','st_lq_league.id','=','st_lq_local_league.lg_id')->select('st_lq_league.id','st_lq_league.name_chinese')->where('st_lq_local_league.source',$source->infocontent)->get();
//        }else{
//            $data = \App\Models\BasketLeague::select('id','name_chinese')->get();
//        }

		$data = \App\Models\BasketLeague::select('id','lg_id','name_chinese')->get();
		if (!$data) {
			return;
		}
		return $data->toArray();
	}
	/**
	 *获取所有国家信息
	 */
	function getCountry() {
		$data = \App\Models\Country::select('country_id','name_chinese')->get();
		if (!$data) {
			return;
		}
		for($i=0;$i<count($data);$i++){
			$data[$i]->home_country_name = $data[$i]->name_chinese;
			$data[$i]->home_country_id = $data[$i]->country_id;
			$data[$i]->guest_country_name = $data[$i]->name_chinese;
			$data[$i]->guest_country_id = $data[$i]->country_id;
		}
		return $data->toArray();
	}
	/**
	 *获取国家的球队信息
	 */
	function getteam() {
		$countryid = $_GET["countryid"];
		$gametype = \App\Models\StGameType::where('game_code','zq')->first();
		$res = \App\Models\Team::where('country_id',$countryid)->where('game_type_id',$gametype->id)->get();
		return json_encode($res);
	}
	/**
	 *添加赛事
	 */
	function add(Req $req) {
		if (!$req->isMethod('post')) {
			$parents = $this->getParent();
			$country = $this->getCountry();
			$countrys = $this->getCountry();
			$lange = trans('menu');
			foreach ($parents as $k => $v) {
				$arr = trim($parents[$k]['name_chinese']);
				if (isset($lange[$arr])) {
					$parents[$k]['name']=$lange[$arr];
				}
			}
			$data['parents'] = $parents;
			$data['country'] = $country;
			$data['countrys'] = $countrys;
			return view('sports.basket_form', $data);
		} else {
			$model = new \App\Models\SportsBasket();
			$model->home_team = $req->input('home_team');
			$model->guest_team = $req->input('guest_team');
			$model->lg_id = $req->input('parent_id');
			$model->match_date = $req->input('match_date');
			$model->match_time = $req->input('match_time');
			$model->status = $req->input('status');
			$model->match_id = time() ;
			$model->ctime = date('Y-m-d H:i:s',time());
			$model->utime = date('Y-m-d H:i:s',time());
			$model->tag = mt_rand(0,100) ;
			$model->source = 'user-defined';

			$db = new \App\Models\Stlqlocalmatch();
			$db->source = 'user-defined';
			$db->match_id = $model->match_id;

			$model->save();
			$db->save();
			return responseToJson(1);

		}
	}

	function view(Req $req) {
		return $this->edit($req);
	}

	/**
	 *修改赛事
	 */
	function edit(Req $req) {
		$id = $req->id;
		if (intval($id) < 1) {
			return -1;
		}
		if (!$req->isMethod('post')) {
			$country = $this->getCountry();
			$countrys = $this->getCountry();
			$data = \App\Models\SportsBasket::where('id', $id)->first();
			if (!$data) {
				return -2;
			}
			//查看赛事是否有下注细信息
			$res = \App\Models\MoneyBuyMatch::where('match_id', $data->match_id)->get()->toArray();
			if(!empty($res)){
				if($data->status == 0){
					$match_status =array(['status'=>0,'name'=>'未开始'],['status'=>1,'name'=>'正在进行'],['status'=>4,'name'=>'作废']);
				}
				if($data->status == 1){
					$match_status =array(['status'=>1,'name'=>'正在进行'],['status'=>2,'name'=>'已结束'],['status'=>4,'name'=>'作废']);
				}
			}else{
				if($data->status == 0){
					$match_status =array(['status'=>0,'name'=>'未开始'],['status'=>1,'name'=>'正在进行'],['status'=>4,'name'=>'作废'],['status'=>6,'name'=>'取消']);
				}
				if($data->status == 1){
					$match_status =array(['status'=>1,'name'=>'正在进行'],['status'=>2,'name'=>'已结束'],['status'=>4,'name'=>'作废'],['status'=>6,'name'=>'取消']);
				}
			}
			if($data->status == 2){
				$match_status =array(['status'=>2,'name'=>'已结束'],['status'=>4,'name'=>'作废']);
			}
			if($data->status == 3){
				$match_status =array(['status'=>3,'name'=>'已结算'],['status'=>5,'name'=>'待结算']);
			}
			if($data->status == 4){
				$match_status =array(['status'=>4,'name'=>'作废'],['status'=>6,'name'=>'取消']);
			}
			if($data->status == 5){
				$match_status =array(['status'=>5,'name'=>'待结算'],['status'=>4,'name'=>'作废']);
			}
			if($data->status == 6){
				$match_status =array(['status'=>6,'name'=>'取消']);
			}

			$name_chinese = \App\Models\BasketLeague::where('lg_id', $data->lg_id)->first();
			$data->name_chinese = $name_chinese->name_chinese;
			$data = $data->toArray();
			$data['parents'] = $this->getParent();
			$data['country'] = $country;
			$data['countrys'] = $countrys;

			$data['match_status'] = $match_status;


			//$lange = trans('menu');
			foreach ($data['parents'] as $k => $v) {
				$arr = trim($data['parents'][$k]['name_chinese']);
				if (isset($lange[$arr])) {
					$data['parents'][$k]['name_chinese']=$lange[$arr];
				}
			}

			return view('sports.basket_form', $data);
		} else {
			$model = new \App\Models\SportsBasket();
			$model->id = $req->input('id');
			$model = $model::find($model->id);
			$model->home_team = $req->input('home_team');
			$model->guest_team = $req->input('guest_team');
//            if(gettype($req->input('parent_id'))=='integer'){
//                $model->lg_id = $req->input('parent_id');
//            }else{
//                $model->name_chinese = $req->input('parent_id');
//                $res = \App\Model\SportsLeague::where('name_chinese',$model->name_chinese)->first();
//                $model->lg_id = $res->lg_id;
//            }
			$model->lg_id = $req->input('parent_id');
			$model->match_date = $req->input('match_date');
			$model->match_time = $req->input('match_time');
			$model->status = $req->input('status');
			$model->ctime = date('Y-m-d H:i:s',time());
			$model->utime = date('Y-m-d H:i:s',time());
			$model->save();
			return responseToJson(1);
		}
	}
	/**
	 *删除赛事
	 */
	public function delete(Req $req) {
		$id = $req->input('id');
		if (empty($id)) {
			return responseToJson(-2001); //id����Ϊ��
		}
		$ids = explode(',', $id);
		if (!is_array($ids) && intval($ids) < 0) {
			return responseToJson(-2002); //id����
		}
		$id = array();
		$localmatch = \App\Models\Stlqlocalmatch::get();
		if (is_array($ids) && count($ids) > 0) {
			foreach ($ids as $k => $v) {
				if (intval($v) < 1) {
					unset($ids[$k]);
				}
				$match = \App\Models\SportsBasket::where('id',$v)->first();
				for($i=0;$i<count($localmatch);$i++){
					if($localmatch[$i]->match_id == $match->match_id){
						$id[] = $localmatch[$i]->id;
					}
				}
			}
		}

		$rows = \App\Models\SportsBasket::whereIn('id', $ids)->delete();
		if (!$rows) {
			return responseToJson(-2003); //id����
		}
		if(count($id)>0) {
			$row = \App\Models\Stlqlocalmatch::whereIn('id', $id)->delete();
			if (!$row) {
				return responseToJson(-2003); //id????
			}
		}
		return responseToJson(1, trans('menu.delete_success')); //id����

	}

	/**
	 *赛事结果处理
	 */
	public function dealwith(Req $req)
	{
		$id = $req->id;
		if (intval($id) < 1) {
			return -1;
		}
		//return $id;
		$SettlementWinFail = new SettlementWinFail();
		$data = $SettlementWinFail->doRun($id);
		return $data;
	}

	function odds(Req $req)
	{
		$cp_id = $req->id;
		$request['status'] = isset($req->status) ? trim($req->status) : '-1';
		$request['p_code'] = isset($req->p_code) ? trim($req->p_code) : '-1';
		$request['match_id'] = isset($req->match_id) ? trim($req->match_id) : null;
		$newapp = \App\Models\SportsBasket::where('id',$cp_id)->first();
		// $match_id = $newapp->match_id;
		if(empty($newapp)){
			$match_id = $req->input('match_id');
		}else{
			$match_id = $newapp->match_id;
		}
		$request['match_id'] = isset($match_id) ? trim($match_id) : null;
		//$data = \App\Model\Matchcode::where('p_id','0')->get();
		$data = \App\Models\Matchcode::where('p_id','0')->where('game_code','lq')->get();
		$request['pcode'] = $data;
		$dt = \App\Lib\DataTable\DataTable::init();
		$dt->setDataSource('/admin/SportsBasket/oddsinfo?match_id='.$match_id.'');
		$dt->setLang('sportssoccer');
		$dt->addColsFields('id', array('templet' => '#userdetail', 'sort' => true, 'width' => 80));
		$dt->addColsFields('match_id', array('templet' => '#userdetail', 'sort' => true, 'width' => 100));
		$dt->addColsFields('odds_code_cn', array('templet' => '#userdetail', 'sort' => false, 'width' => 200));
		$dt->addColsFields('condition', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
		$dt->addColsFields('odds', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
//        $dt->addColsFields('p_id', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
		$dt->addColsFields('p_code_cn', array('templet' => '#userdetail', 'sort' => false, 'width' => 120));
		$dt->addColsFields('max', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
		$dt->addColsFields('min', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
		$dt->addColsFields('status', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
		$dt->addColsFields('expire_time', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
		if (checkRriv('/admin/SportsBasket/oddsedit?id='.$cp_id.'')) {
			$arr[] = 'oddsedit';
		}
		$dt->setToolBar($arr, array('width' => 150));
		$dt->enableCheckBox();

		return view('sports/basket_odds', $dt->render($request));
	}

	function oddsinfo(Req $req){
		$lange = trans('sportsoddscode');
		$match_id = $req->match_id;
		$p_code = Request::has('p_code') ? Request::get('p_code') : '';
		$status = Request::has('status') ? Request::get('status') : '';
		$where = array();
		if (!empty($p_code) && $p_code!=-1) {
			$where[] = array('st_lq_odds.p_code', '=', $p_code);
		}
		if (!empty($status) && $status != -1) {
			$where[] = array('st_lq_odds.status', '=', $status);
		}

		if (intval($match_id) < 1) {
			return -1;
		}
		$new = new \App\Models\BasketOdds();
		$data = $new->getodds($match_id,$where);

//		foreach ($data as $k => $v) {
//			$odds_code = trim($data[$k]['odds_code']);
//			$p_code = trim($data[$k]['p_code']);
//			if (isset($lange[$odds_code])) {
//				$data[$k]['odds_code']=$lange[$odds_code];
//			}
//			if (isset($lange[$p_code])) {
//				$data[$k]['p_code']=$lange[$p_code];
//			}
//		};

		return \App\Lib\DataTable\DataTable::init()->toJson($data);
	}
	/**
	 *根据选择的父级赔率代码获取对应的子级赔率代码
	 */
	function getoddscode() {
		$p_code = $_GET["pcode"];
		$res = \App\Models\Matchcode::where('odds_code',$p_code)->first();
		$codedata = \App\Models\Matchcode::where('p_id',$res->id)->get();
		return json_encode($codedata);
	}
	/**
	 *添加赔率
	 */
	function addodds(Req $req) {
		//$pcodedata = \App\Model\Matchcode::where('p_id','0')->get();
		$pcodedata = \App\Models\Matchcode::where('p_id','0')->where('game_code','lq')->get();
		for($i=0;$i<count($pcodedata);$i++){
			$pcodedata[$i]->p_code = $pcodedata[$i]->odds_code;
		}

		if (!$req->isMethod('post')) {
			$cp_id = $_SERVER['QUERY_STRING'];  //获取url中的参数--赛事id
			$data = ["match_id"=>$cp_id];
			$data['pcode'] = $pcodedata;
			return view('sports.basket_odds_form',$data);
		} else {
			$model = new \App\Models\BasketOdds();
			$date = new \App\Models\BasketOddsRecord();
			$model->match_id = $req->input('match_id');
			$model->odds_code = $req->input('code');
			$model->status = $req->input('status');
			$model->p_code = $req->input('pcode');
			$res = \App\Models\Matchcode::where('odds_code',$model->p_code)->first();
			$model->p_id = $res->id;
			$result = \App\Models\BasketOdds::where('odds_code',$model->odds_code)->where('p_id',$model->p_id)->orderby('utime','desc')->first();
			if(!empty($result)){
				$sort = $result->sort;
				$model->sort = $sort+1;
			}else{
				$model->sort = 0;
			}
			$model->odds = $req->input('odds');
			$model->condition = $req->input('condition');
			$model->max = $req->input('max');
			$model->min = $req->input('min');
			$model->ctime = date('Y-m-d H:i:s',time());
			$model->utime = date('Y-m-d H:i:s',time());
			$model->sole = md5($model->match_id.$model->odds_code.$model->sort.$model->p_id.$model->ctime);
			$model->source = 'user-defined';
			$lg_id = \App\Models\SportsBasket::where('match_id',$model->match_id)->first();
			if(!empty($lg_id)){
				$model->lg_id = $lg_id->lg_id;
			}
			$model->expire_time = $req->input('expire_time');
			$model->odds_only = md5($model->match_id.$model->odds_code.$model->ctime);

			$date->match_id = $model->match_id;
			$date->odds_code = $model->odds_code;
			$date->status = $model->status;
			$date->p_code = $model->p_code;
			$date->p_id = $model->p_id;
			$record = \App\Models\BasketOddsRecord::where('odds_code',$date->odds_code)->where('p_id',$date->p_id)->orderby('utime','desc')->first();
			if(!empty($record)){
				$sort = $record->sort;
				$date->sort = $sort+1;
			}else{
				$date->sort = 0;
			}
			$date->odds = $model->odds;
			$date->condition = $model->condition;
			$date->max = $model->max;
			$date->min = $model->min;
			$date->ctime = $model->ctime;
			$date->utime = $model->utime;
			$date->source = $model->source;
			$date->lg_id = $model->lg_id;
			$date->odds_only = $model->odds_only;

			$model->save();
			$date->save();
			return responseToJson(1);
		}
	}
	/**
	 *修改赔率
	 */
	function oddsedit(Req $req) {
		//$pcodedata = \App\Model\Matchcode::where('p_id','0')->get();
		$pcodedata = \App\Models\Matchcode::where('p_id','0')->where('game_code','lq')->get();
		for($i=0;$i<count($pcodedata);$i++){
			$pcodedata[$i]->p_code = $pcodedata[$i]->odds_code;
		}
		$id = $req->id;
		if (intval($id) < 1) {
			return -1;
		}
		if (!$req->isMethod('post')) {

			$data = \App\Models\BasketOdds::where('id', $id)->first();
			if (!$data) {
				return -2;
			}
			//$res = \App\Model\Matchcode::where('odds_code', $data->odds_code)->where('game_type','lq')->first();
			$res = \App\Models\Matchcode::where('odds_code', $data->odds_code)->first();
			if(!empty($res)){
				$data->odds_name = $res->odds_name;
			}

			$expire_time = $data->expire_time; //2019-04-15 21:10:00
			$str1 = str_replace(" ","T",$expire_time);
			$data->expire_time = $str1;

			$odds_code = trim($data->odds_code);
			$p_code = trim($data->p_code);
			if (isset($lange[$odds_code])) {
				$data->odds_code_cn=$lange[$odds_code];
			}
			if (isset($lange[$p_code])) {
				$data->p_code_cn=$lange[$p_code];
			}
			$data = $data->toArray();

			$data['pcode'] = $pcodedata;
			//$data['code'] = $codedata;

			return view('sports.basket_odds_form', $data);
		} else {
			$model = new \App\Models\BasketOdds();
			$data = new \App\Models\BasketOddsRecord();
			$model->id = $req->input('id');
			$model = $model::find($model->id);
			$model->odds_code = $req->input('code');
			$model->status = $req->input('status');
			$model->p_code = $req->input('pcode');
			$model->odds = $req->input('odds');
			$model->condition = $req->input('condition');
			$model->max = $req->input('max');
			$model->min = $req->input('min');
			$model->ctime = date('Y-m-d H:i:s',time());
			$model->utime = date('Y-m-d H:i:s',time());
			$model->expire_time = $req->input('expire_time');
			$model->odds_only = md5($model->match_id.$model->odds_code.$model->ctime);

			$result = \App\Models\BasketOdds::where('id',$model->id)->first();
			$data->match_id = $result->match_id;
			$data->odds_code = $model->odds_code;
			$data->status = $model->status;
			$data->p_code = $model->p_code;
			$data->p_id = $model->p_id;
			$record = \App\Models\BasketOddsRecord::where('match_id',$data->match_id)->where('odds_code',$data->odds_code)->where('p_id',$data->p_id)->orderby('utime','desc')->first();
			if(!empty($record)){
				$sort = $record->sort;
				$data->sort = $sort+1;
			}else{
				$data->sort = 0;
			}
			$data->odds = $model->odds;
			$data->condition = $model->condition;
			$data->max = $model->max;
			$data->min = $model->min;
			$data->ctime = $model->ctime;
			$data->utime = $model->utime;
			$data->source = $result->source;
			$data->lg_id = $result->lg_id;
			$data->odds_only = $result->odds_only;

			$model->save();
			$data->save();
			return responseToJson(1);
		}

	}
	/**
	 *删除赔率
	 */
	public function oddsdelete(Req $req) {
		$id = $req->input('id');
		if (empty($id)) {
			return responseToJson(-2001); //id����Ϊ��
		}
		$ids = explode(',', $id);
		if (!is_array($ids) && intval($ids) < 0) {
			return responseToJson(-2002); //id����
		}
		if (is_array($ids) && count($ids) > 0) {
			foreach ($ids as $k => $v) {
				if (intval($v) < 1) {
					unset($ids[$k]);
				}
			}
		}

		$rows = \App\Models\BasketOdds::whereIn('id', $ids)->delete();
		if (!$rows) {
			return responseToJson(-2003); //id����
		}
		return responseToJson(1, trans('menu.delete_success')); //id����

	}
}