<?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\SettlementOrder;
use App\Models;
use Request;

/**
 *
 */
class SportsfootController extends Controller {

	//足球结果列表
	function outcome(Req $req) {
		$request=array();
		$request['home_team'] = isset($req->home_team) ? trim($req->home_team) : null;
		$request['status'] = isset($req->status) ? trim($req->status) : '-1';
		$request['sureblurs'] = isset($req->sureblurs) ? $req->sureblurs : 'on';
		$request['source'] = isset($req->source) ? $req->source : null;
		$request['name_chinese'] = isset($req->name_chinese) ? $req->name_chinese : null;
		$request['star_time'] = isset($req->star_time) ? trim($req->star_time) :trans('status.default_time.seven_day') ;
        $request['end_time'] = isset($req->end_time) ? trim($req->end_time) : trans('status.default_time.etime');
        $newapp = new \App\Models\SoccerLeague();
		$data = $newapp->allleague();
        $request['league'] = $data;//联赛id

        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/sportsfoot/outcomeinfo');
        $dt->setLang('sportsfoot');
        $dt->addColsFields('newtime', array('templet' => '#newtime', 'sort' => false, 'width' => 200));
        $dt->addColsFields('totime', array('templet' => '#totime', 'sort' => false, 'width' => 180));
        $dt->addColsFields('home_team', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
		$dt->addColsFields('guest_team', array('templet' => '#userdetail', 'sort' => false, 'width' => 70));
		$dt->addColsFields('dsnum', array('templet' => '#dsnum', 'sort' => false, 'width' => 70));
		$dt->addColsFields('csnum', array('templet' => '#csnum', 'sort' => false, 'width' => 110));
		$dt->addColsFields('sxalfcourt', array('templet' => '#sxalfcourt', 'sort' => false, 'width' => 300));
        $dt->addColsFields('statusmatch', array('templet' => '#statusmatch', 'sort' => false, 'width' => 150,'align' => 'left'));
		$dt->addColsFields('operation', array('templet' => '#status', 'sort' => false, 'width' => 300));
        // $arr[] = 'view';
		// if (checkRriv('/admin/sportsfoot/edit')) {
		// 	$arr[] = 'edit';
		// }
		// $dt->setToolBar($arr, array('width' => 200));
        $dt->enableCheckBox();
		
		return view('admin.sportsfoot/outcome', $dt->render($request));
	}

	//结果添加
	function addend(Req $req){
		$match_id = $req->matchid;
		$model = \App\Models\Stzqresult::where('match_id', $match_id)->first();

		$penaltycard = array(
        	'home'=>intval($req->homeallcard)?intval($req->homeallcard):0,
        	'guest'=>intval($req->guestallcard)?intval($req->guestallcard):0,
        	'home_half'=>intval($req->homehalfcard)?intval($req->homehalfcard):0,
        	'guest_half'=>intval($req->guesthalfcard)?intval($req->guesthalfcard):0,
        );
        $cornerball = array(
        	'home'=>intval($req->homeallcorner)?intval($req->homeallcorner):0,
        	'guest'=>intval($req->guestallcorner)?intval($req->guestallcorner):0,
        	'home_half'=>intval($req->homehalfcorner)?intval($req->homehalfcorner):0,
        	'guest_half'=>intval($req->guesthalfcorner)?intval($req->guesthalfcorner):0,
        );

		$model->first_score = $req->firstscore;
		$model->last_score = $req->lastscore;
		$model->match_winer = $req->matchwiner;
		$model->penalty_card = json_encode($penaltycard);
		$model->corner_ball = json_encode($cornerball);

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

	//查询赛事结果
	function Matchresult(Req $req){
		$match_id = $req->match_id;
		$newapp = \App\Models\Stzqresult::where('match_id', $match_id)->first();

		$array =array(
			'corner_ball' => json_decode($newapp['corner_ball'],true),
			'penalty_card' => json_decode($newapp['penalty_card'],true),
			'newapp' => $newapp,
		);
		return $array;
	}

	//结算
	function Settlement(Req $req){
		//查询赛事下所有订单
		$ssid = $req->match_id;//赛事id
		$type = $req->type;//是否再结算1,首次结算2,再次结算
		$newapp = new \App\Models\MoneyBuyMatch();
		$simplex_ids = array_column($newapp->allsimplexorder($ssid,'zq'),'order_id');
		$str_ids = array_column($newapp->allstrorder($ssid),'order_id');

		$update = $this->addcomendnotice($ssid); 
		if($update['status']==1){
			$SettlementOrder = new SettlementOrder();
	        $SettlementOrder->reSettlement($str_ids, 2,$type,'zq',$ssid);//串式
	        $data = $SettlementOrder->reSettlement($simplex_ids, 1,$type,'zq',$ssid);//单式注单
	        return responseToJson($data);
	    }else{
	    	return responseToJson($update);
	    }
	}

	//作废
	function revoke(Req $req){
		$match_id = $req->match_id;//赛事id
		$model = \App\Models\Stzqresult::where('match_id', $match_id)->first();
		$model->status = 4;
		$model->save();

		$smodel = \App\Models\SportsSoccer::where('match_id', $match_id)->first();
		if($smodel){
			$smodel->status = 4;
			$smodel->save();
		}

		$upapp = new \App\Models\SportsNoteList();
        $data = $upapp->updatesimplex($match_id,'zq');//修改单式状态

        //单式撤单返现
        $newapp = new \App\Models\MoneyBuyMatch();
		$all = $newapp->allsimplexorder($match_id,'zq');
        for ($i=0; $i < count($all); $i++) { 
	        $appgx = new \App\Lib\Settlement\SettlementOrder();
	        $appgx->insertData($all[$i]['order_id'], $all[$i]['money'], $all[$i]['account_identity'], '1', 'zq', $all[$i]['info_identity'], $all[$i]['money'],$all[$i]['match_id']);
        }

        //串式撤单只改状态
        $str_ids = array_column($newapp->allstrorder($match_id),'order_id');
        $csapp = new \App\Models\MoneyBuyStr();
        $csapp->updatestatus($str_ids);//var_dump($ss);die;
        //修改money_buy_match 投注结果result=2为平
        $newapp->updatast($match_id);
        
		return responseToJson(1);
	}

	//赛事结果修改
	function edit(Req $req) {
		$id = $req->id;
		if (intval($id) < 1) {
			return -1;
		}
		if (!$req->isMethod('post')) {

			$data = \App\Models\Stzqresult::where('id', $id)->first();
			if (!$data) {
				return -2;
			}
			$data = $data->toArray();

			return view('admin.sportsfoot/edit', $data);
		} else {
			$model = \App\Models\Stzqresult::where('id', $id)->first();
			$model->home_team = $req->input('home_team');
			$model->guest_team = $req->input('guest_team');
			$model->home_rate = $req->input('home_rate');
			$model->guest_rate = $req->input('guest_rate');
			$model->status = $req->input('status');
			//$model->update_time = time();
			$model->save();
			return responseToJson(1);
		}
	}

	function outcomeinfo() {
		$page = Request::has('page') ? Request::get('page') : '';
		$list = Request::has('limit') ? Request::get('limit') : 10;
		$home_team = Request::has('home_team') ? Request::get('home_team') : '';
		$sureblur = Request::has('sureblurs') ? Request::get('sureblurs') : 'off';
		$status = Request::has('status') ? Request::get('status') : '';
		$source = Request::has('source') ? Request::get('source') : 'hg3535';
        $star_time = Request::get('star_time') ? Request::get('star_time').' 00:00:00' : '';
        $end_time = Request::get('end_time') ? Request::get('end_time').' 23:59:59' : '';
        $name_chinese = Request::has('name_chinese') ? Request::get('name_chinese') : '';

		$where = array();
		$orwhere = array();
		if (!empty($home_team)) {
			if (empty($sureblur) || $sureblur == 'off') {
				$where[] = array('st_zq_result.home_team', 'like', '%' . $home_team . '%');
				$orwhere[] = array('st_zq_result.guest_team', 'like', '%' . $home_team . '%');
			} else {
				$where[] = array('st_zq_result.home_team', '=', $home_team);
				$orwhere[] = array('st_zq_result.guest_team', '=', $home_team);
			}
		}
		if ($status != -1) {
			$where[] = array('st_zq_result.status', '=', $status);
		}
		if (!empty($source)) {
			$where[] = array('st_zq_result.source', '=', $source);
		}
		if (!empty($name_chinese)) {
			$where[] = array('st_zq_league.name_chinese', '=', $name_chinese);
		}
		if (!empty($star_time)) {
            $star_time = date('Y-m-d H:i:s', strtotime($star_time));
            $where[] = array('st_zq_result.start_time', '>', $star_time);
        }
        if (!empty($end_time)) {
            $end_time = date('Y-m-d H:i:s', strtotime($end_time));
            $where[] = array('st_zq_result.start_time', '<', $end_time);
        }
        $newapp = new \App\Models\Stzqresult();
        $data = $newapp->resultlist($list, $page, $where, $orwhere);
        
        return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total']);
    }

    //
    function saislist(Req $req){
    	$lgid = $req->lgid;//赛事id
		$newstzqcompetition = new \App\Models\Stzqcompetition();
		$league_data = $newstzqcompetition->allcompetition($lgid);//赛事id

		return $league_data;
    }
    
	//赛事结果添加  guest_score 客队进球  all_goal总进球数
    function addoutcome(Req $req) {
		if (!$req->isMethod('post')) {
            $lange = trans('menu');
			$newapp = new \App\Models\SoccerLeague();
			$league_data = $newapp->allleague();//联赛id

            return view('admin.sportsfoot/addoutcome',['data'=>$league_data]);
        } else {
        	$match_id = trim($req->input('match_id'));//赛事id
        	//添加足球比赛结果表
        	$alldata = $req->input();
        	unset($alldata['_token']);
        	$all_goal = intval($alldata['home_score'])+intval($alldata['guest_score']);//总进球数
        	$penaltycard = array(
        		'home'=>intval($alldata['homeallcard'])?intval($alldata['homeallcard']):0,
        		'guest'=>intval($alldata['guestallcard'])?intval($alldata['guestallcard']):0,
        		'home_half'=>intval($alldata['homehalfcard'])?intval($alldata['homehalfcard']):0,
        		'guest_half'=>intval($alldata['guesthalfcard'])?intval($alldata['guesthalfcard']):0,
        	);
        	$cornerball = array(
        		'home'=>intval($alldata['homeallcorner'])?intval($alldata['homeallcorner']):0,
        		'guest'=>intval($alldata['guestallcorner'])?intval($alldata['guestallcorner']):0,
        		'home_half'=>intval($alldata['homehalfcorner'])?intval($alldata['homehalfcorner']):0,
        	'guest_half'=>intval($alldata['guesthalfcorner'])?intval($alldata['guesthalfcorner']):0,
        	);

        	$ret = \App\Models\Stzqresult::updateOrCreate(['match_id'=>$match_id],array_merge($alldata,['match_time'=>'00:01','update_time'=>date('Y-m-d H:i:s'),'all_goal'=>$all_goal,'penalty_card'=>json_encode($penaltycard),'corner_ball'=>json_encode($cornerball)]));
        	//添加足球比赛结果记录表
        	$ret = \App\Models\Stzqresultrecord::updateOrCreate(['match_id'=>$match_id,'update_time'=>date('Y-m-d H:i:s')],array_merge($alldata,['match_time'=>'00:01','update_time'=>date('Y-m-d H:i:s')]));
        }
        return responseToJson(1); 
    }

    //删除赛事结果
	function deleteoutcome(Req $req) {
		$id = $req->input('id');
		if (empty($id)) {
			return responseToJson(-2001); //
		}
		$ids = explode(',', $id);
		if (!is_array($ids) && intval($ids) < 0) {
			return responseToJson(-2002); //
		}
		if (is_array($ids) && count($ids) > 0) {
			foreach ($ids as $k => $v) {
				if (intval($v) < 1) {
					unset($ids[$k]);
				}
			}
		}
		// echo '敬请期待';die;
		$rows = \App\Models\Stzqresult::whereIn('id', $ids)->delete();
		if (!$rows) {
			return responseToJson(-2003); 
		}
		return responseToJson(1); 
	}

	//更新赛事比分
	function updatenum(Req $req){
		$type = $req->type;
		$id = $req->id;
		$num = $req->num;
		$match_id = $req->match_id;
		$newapp = new \App\Models\Stzqresult();
		$update = $this->addcomendnotice($match_id);
		if($update['status']==1){
			if($type==1){
				$data['u_home_score'] = $num;
				$res = $newapp->updateInfo($data,$id);//联赛id
			}else if($type==2){
				$data['u_guest_score'] = $num;
				$res = $newapp->updateInfo($data,$id);//联赛id
			}else if($type==3){
				$data['home_score'] = $num;
				$res = $newapp->updateInfo($data,$id);//联赛id
			}else{
				$data['guest_score'] = $num;
				$res = $newapp->updateInfo($data,$id);//联赛id
			}
			$newapp->totalgoal($match_id);
			$update = $this->addcomendnotice($match_id);
			return responseToJson($res);
		}else{
			return responseToJson($update);
		}
	}

	//添加赛事结束纪录
	function addcomendnotice($match_id){
		$data = \App\Models\Comendnotice::where(['match_id'=>$match_id,'game_code'=>'zq'])->first();
		if(!$data){
			$model = new \App\Models\Comendnotice();
			$model->status = 0;//联赛id
			$model->game_code = 'zq';
			$model->match_id = $match_id;//赛事id
			$model->ctime = date('Y-m-d H:i:s');
			$model->save();

			$newapp = new \App\Lib\Settlement\SettlementWinFail();
			$ret = $newapp->doRun($model->id);
		}else{
			$newapp = new \App\Lib\Settlement\SettlementWinFail();
            \App\Models\Comendnotice::where(['match_id'=>$match_id,'game_code'=>'zq'])->update(['status'=>0]);
			$ret = $newapp->doRun($data->toArray()['id']);
			$ret2 =$data->toArray()['id'];
            if ($ret2['status']==1){
                \App\Models\Comendnotice::where(['match_id'=>$match_id,'game_code'=>'zq'])->update(['status'=>4]);
            }
		}
		return $ret;
	}
	
	
}