<?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 SportswqController extends Controller {
	public $code = "wq";

	//网球结果列表
	public 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['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/Sportswq/outcomeinfo');
        $dt->setLang('sportswq');
        $dt->addColsFields('newtime', array('templet' => '#newtime', 'sort' => false, 'width' => 200));
        $dt->addColsFields('start_time', array('templet' => '#home_team', 'sort' => false, 'width' => 155));
        $dt->addColsFields('home_player_name', array('templet' => '#home_team', 'sort' => false, 'width' => 130));
        $dt->addColsFields('guest_player_name', array('templet' => '#guest_team', 'sort' => false, 'width' => 130));
        $dt->addColsFields('dsnum', array('templet' => '#dsnum', 'sort' => false, 'width' => 80));
        $dt->addColsFields('csnum', array('templet' => '#home_rate', 'sort' => false, 'width' => 80));
        $dt->addColsFields('match_score', array('templet' => '#matchscore', 'sort' => false, 'width' => 160));
        $dt->addColsFields('statusmatch', array('templet' => '#statusmatch', 'sort' => false, 'width' => 80));
        $dt->addColsFields('operation', array('templet' => '#operation', 'sort' => false, 'width' => 300));
        return view('admin.Sportswq/outcome', $dt->render($request));
	}

	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') : '';
        $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_wq_result.home_player_name', 'like', '%' . $home_team . '%');
				$orwhere[] = array('st_wq_result.guest_player_name', 'like', '%' . $home_team . '%');
			} else {
				if(is_numeric($home_team)){
					$where[] = array('st_wq_result.match_id', '=', $home_team);
                    $orwhere[] = array('st_wq_result.match_id', '=', $home_team);
				}else{
					$where[] = array('st_wq_result.home_player_name', '=', $home_team);
					$orwhere[] = array('st_wq_result.guest_player_name', '=', $home_team);
				}
			}
		}

        if (!empty($star_time) and empty($home_team)) {
            $star_time = date('Y-m-d H:i:s', strtotime($star_time));
            $where[] = array('st_wq_result.start_time', '>', $star_time);
            $orwhere[] = array('st_wq_result.start_time', '>', $star_time);
        }
        if (!empty($end_time) and empty($home_team)) {
            $end_time = date('Y-m-d H:i:s', strtotime($end_time));
            $where[] = array('st_wq_result.start_time', '<', $end_time);
            $orwhere[] = array('st_wq_result.start_time', '<', $end_time);
        }

		if ($status != -1) {
			$where[] = array('st_wq_result.status', '=', $status);
			$orwhere[] = array('st_wq_result.status', '=', $status);
		}
		if (!empty($name_chinese)) {
			$where[] = array('st_wq_result.name_chinese', '=', $name_chinese);
			$orwhere[] = array('st_wq_result.name_chinese', '=', $name_chinese);
		}

        $newapp = new \App\Models\Stwqresult();
        $data = $newapp->resultlist($list, $page, $where, $orwhere);
        
        return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total']);
	}

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

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

		//赛事下单式注单作废，串关注单下此赛事按平局处理
		$upapp = new \App\Models\SportsNoteList();
		$upapp->delorder($match_id,'wq');

//		$upapp = new \App\Models\SportsNoteList();
//        $data = $upapp->updatesimplex($match_id,'wq');//修改单式状态
//
//        //单式撤单返现
//        $newapp = new \App\Models\MoneyBuyMatch();
//		$all = $newapp->allsimplexorder($match_id,'wq');
//        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', 'wq', $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 Settlement(Req $req){
		$jsurl = config('sconstant.url');//结算请求域名地址
		$match_id = $req->match_id;
		$type = $req->type;
		$token = session('adminInfo.token');
		$notice = \App\Models\Comendnotice::where('match_id', $match_id)->first();
		$noticeid = $notice['id'];
		if(!$notice){
			return json_encode(['status'=>5,'msg'=>'请先核对结果,并提交结果']);
		}
		//查询赛事单式是否有订单(篮球)
		$newapp = new \App\Models\MoneyBuyMatch();
		$simplex_ids = array_column($newapp->allsimplexorder($match_id,'wq'),'order_id');
		$str_ids = array_column($newapp->allstrorder($match_id),'order_id');

		if(count($simplex_ids)>0 || count($str_ids)>0){
			$requet = file_get_contents($jsurl."/WinFail?noticeid=".$noticeid."&token=".$token);
			
			if(json_decode($requet,true)['status']==1){
			    $napp = new \App\Models\Stzqresult();
				//单式结算
				if(count($simplex_ids)>0 && count($str_ids)==0){
					$huawei_res = $napp->simplexs($token,$match_id,$jsurl,'wq');
					
					if($huawei_res['status']==1){
						return json_encode(['status'=>1,'msg'=>'单式结算成功,没有串式订单']);
					}else{
						return json_encode(['status'=>3,'msg'=>'单式结算有误,请联系管理员!!!('.$huawei_res['msg'].')']);//结算错误
					}
				}elseif(count($str_ids)>0 && count($simplex_ids)==0){
					//串式结算
					$tandem_res = $napp->tandems($token,$match_id,$jsurl,'wq');

					if($tandem_res['status']==1){
						return json_encode(['status'=>1,'msg'=>'串式结算成功,没有单式订单']);
					}else{
						return json_encode(['status'=>3,'msg'=>'串式结算有误,请联系管理员!!!('.$tandem_res['msg'].')']);//结算错误
					}
				}elseif(count($str_ids)>0 && count($simplex_ids)>0){
					//既有单式又有串式
					$huawei_res = $napp->simplexs($token,$match_id,$jsurl,'wq');

					//串式结算
					$tandem_res = $napp->tandems($token,$match_id,$jsurl,'wq');
					if($tandem_res['status']==1 && $huawei_res['status']==1){
						return json_encode(['status'=>1,'msg'=>'结算成功']); 
					}elseif($tandem_res['status']!=1 || $huawei_res['status']!=1){
						return json_encode(['status'=>3,'msg'=>'结算有误,请联系管理员!!!('.$tandem_res['msg'].$huawei_res['msg'].')']);
					}else{
						return json_encode(['status'=>3,'msg'=>'返回参数不对']); 
					}
				}
			}else{
				return json_encode(['status'=>2,'msg'=>'判断输赢错误,请联系管理员!!!']);;//输赢错误
			}
		}else{
			$res = \App\Models\Stwqresult::where ('match_id', $match_id)->update(['status' =>3]);
			$res = \App\Models\SportsTennis::where ('match_id', $match_id)->update(['status' =>3]);
            return json_encode(['status'=>4,'msg'=>'该赛事没有任何订单,将会结束该赛事!!!']);
		}
	}

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

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

    //查询赛事结果
    function resultLog(Req $req){
        $match_id = $req->match_id;
        $list = \App\Models\Stwqresultlog::leftJoin('system_user', 'user_id', '=', 'system_user.id')
            ->select('st_wq_result_log.*', 'system_user.loginname')->where('match_id', $match_id)->orderBy('id', 'asc')->get();
        foreach ($list as $key=>$value){
            $list[$key]['inning'] = json_decode($value['inning'], true);
        }
        $result =array(
            'status' => 200,
            'list' => $list
        );
        echo json_encode($result);die;
    }

	function onlyresult(Req $req){
		$match_id = $req->matchid;
		$newapp = \App\Models\Stwqresult::where('match_id', $match_id)->first();
		return $newapp;
	}

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

		$data = array(
			"1" => array(
				'home' => intval($req->homeo)?intval($req->homeo):0,
				'guest' => intval($req->guesto)?intval($req->guesto):0,
			),
			"2" => array(
				'home' => intval($req->homet)?intval($req->homet):0,
				'guest' => intval($req->guestt)?intval($req->guestt):0,
			),
			"3" => array(
				'home' => intval($req->homes)?intval($req->homes):0,
				'guest' => intval($req->guests)?intval($req->guests):0,
			),
			"4" => array(
				'home' => intval($req->homef)?intval($req->homef):0,
				'guest' => intval($req->guestf)?intval($req->guestf):0,
			),
			"5" => array(
				'home' => intval($req->homee)?intval($req->homee):0,
				'guest' => intval($req->gueste)?intval($req->gueste):0,
			),
		);

		\App\Models\Stwqresult::where('match_id', $match_id)->update(["inning"=>json_encode($data)]);

        //添加赛事结果记录
        $lastLog = \App\Models\Stwqresultlog::where([
            ['match_id', $match_id],
            ['type', 1]
        ])->orderBy('id', 'asc')->first();
        if(empty($lastLog) || $lastLog['inning'] != json_encode($data)){
            \App\Models\Stwqresultlog::insert([
                'match_id' => $match_id,
                'inning' => json_encode($data),
                'user_id' => session('adminInfo.admin_id'),
                'type' => 1,
                'create_at' => now()
            ]);
        }

        return responseToJson(1);
	}

	//修改添加赛事比分
	function updatascore(Req $req){
		$match_id = $req->match_id;//节数唯一标识

		$model = \App\Models\Stwqresult::where('match_id', $match_id)->first();
		$model->update_time = date('Y-m-d H:i:s');
		$model->home_player_score = intval($req->home_player_score)?intval($req->home_player_score):0;//主队比分
		$model->guest_player_score = intval($req->guest_player_score)?intval($req->guest_player_score):0;//客队比分
		$model->is_correct = 1;//追加手动更改标识
		$model->save();

		$addnew = new \App\Models\Comendnotice();
		$addnew->addcomendnotice($match_id,'wq');

		$twoapp = new \App\Models\SportsBasket();
		$twoapp->updatestatus('match_id',$match_id,['status'=>2]);//修改赛事状态
		$newapp = new \App\Models\Stwqresult();
		$newapp->updatestatus('match_id',$match_id,['status'=>2]);//修改结果状态

        //添加赛事结果比较记录
        $lastLog = \App\Models\Stwqresultlog::where([
            ['match_id', $match_id],
            ['type', 2]
        ])->orderBy('id', 'desc')->first();

        if(empty($lastLog) || !(
                $lastLog['home_player_score'] == $model->home_player_score
                && $lastLog['guest_player_score'] == $model->guest_player_score
            )){
            $logData = [
                'home_player_score' => $model->home_player_score,
                'guest_player_score' => $model->guest_player_score
            ];
            $logData['type'] = 2;
            $logData['match_id'] = $match_id;
            $logData['user_id'] = session('adminInfo.admin_id');
            $logData['create_at'] = now();
            \App\Models\Stwqresultlog::insert($logData);
        }
		return responseToJson(1); 
	}



}