<?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;
use App\Lib\Biz\Sport\Common as commonFunction;


/**
 *篮球结果结算
 */
class SportsbkController extends Controller {
	public $code = "lq";
	//篮球结果列表
	public function outcome(Req $req) {
		$request['home_team'] = isset($req->home_team) ? trim($req->home_team) : null;
		$request['status'] = isset($req->status) ? trim($req->status) : '-1';
		$request['if_order'] = isset($req->if_order) ? trim($req->if_order) : '1';
		$request['sureblurs'] = isset($req->sureblurs) ? $req->sureblurs : 'on';
		$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');
		$dt = \App\Lib\DataTable\DataTable::init();
		$dt->setDataSource('/admin/Sportsbk/info');
		$dt->setLang('sportsbk');
		$dt->addColsFields('lg_id', array('templet' => '#liansai', 'sort' => true, 'width' => 160));
		$dt->addColsFields('start_time', array('templet' => '#userdetail', 'sort' => true, 'width' => 160));
		$dt->addColsFields('home_team', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
		$dt->addColsFields('guest_team', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
		$dt->addColsFields('dsnum', array('templet' => '#dsnum', 'sort' => false, 'width' => 100));
		$dt->addColsFields('csnum', array('templet' => '#csnum', 'sort' => false, 'width' => 100));
		$dt->addColsFields('match_score', array('templet' => '#match_score','sort' => false, 'width' => 170));
//		$dt->addColsFields('sectionone_two', array('templet' => '#sectionone_two', 'sort' => false, 'width' => 170));
//		$dt->addColsFields('sectionthere_four', array('templet' => '#sectionthere_four', 'sort' => false, 'width' => 220));
		$dt->addColsFields('status', array('templet' => '#matchstatus', 'sort' => false, 'width' => 80));
		$dt->addColsFields('operation', array('templet' => '#operation', 'sort' => false, 'width' => 300));
        $dt->enableCheckBox();
		// if (checkRriv('/admin/Sportsbk/edit')) {
		// 	$arr[] = 'edit';
		// }
		// $dt->setToolBar($arr, array('width' => 200));
		// $dt->enableCheckBox();
		return view('admin/sportsbk/outcome', $dt->render($request));
	}

	//篮球赛事作废
	function revoke(Req $req){
		$match_id = $req->match_id;//赛事id
		\App\Models\Stlqresult::where('match_id', $match_id)->update(['status'=>4]);
		\App\Models\SportsBasket::where('id', $match_id)->update(['status'=>4]);

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

//		$upapp = new \App\Models\SportsNoteList();
//        $data = $upapp->updatesimplex($match_id,$this->code);//修改单式状态
//
//        //单式撤单返现
//        $newapp = new \App\Models\MoneyBuyMatch();
//		$all = $newapp->allsimplexorder($match_id,$this->code);
//        for ($i=0; $i < count($all); $i++) {
//	        $appgx = new 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);
//        //修改money_buy_match 投注结果result=2为平
//        $newapp->updatast($match_id);
        
		return responseToJson(1);
	}

	//结果添加
	function addend(Req $req){
		$match_id = $req->matchid;
		$model = \App\Models\Stlqresult::where('match_id', $match_id)->first();
		$match = \App\Models\SportsBasket::where('id', $match_id)->first();
		$match_status = $match['status'];

		$data = array(
			"1" => array(
				'home' => strlen($req->homeo)?$req->homeo:'',
				'guest' => strlen($req->guesto)?$req->guesto:'',
			),
			"2" => array(
				'home' => strlen($req->homet)?$req->homet:'',
				'guest' => strlen($req->guestt)?$req->guestt:'',
			),
			"3" => array(
				'home' => strlen($req->homes)?$req->homes:'',
				'guest' => strlen($req->guests)?$req->guests:'',
			),
			"4" => array(
				'home' => strlen($req->homef)?$req->homef:'',
				'guest' => strlen($req->guestf)?$req->guestf:'',
			),
			"5" => array(
				'home' => strlen($req->homeu)?$req->homeu:'',
				'guest' => strlen($req->guestu)?$req->guestu:'',
			),
			"6" => array(
				'home' => strlen($req->homeb)?$req->homeb:'',
				'guest' => strlen($req->guestb)?$req->guestb:'',
			),
			"all" => array(
				'home' => strlen($req->homen)?$req->homen:'',
				'guest' => strlen($req->guestn)?$req->guestn:'',
			),
		);

		//修改蓝球比分前的比分数据
		$res = \App\Models\Stlqresult::where('match_id', $match_id)->first();
		$scores = json_decode($res['manual_result'],true);
		$process = array();//进程
		if($scores[1]['home'] != $data[1]['home'] || $scores[1]['guest'] != $data[1]['guest']){
			$process[] = 'one';
		}
		if($scores[2]['home'] != $data[2]['home'] || $scores[2]['guest'] != $data[2]['guest']){
			$process[] = 'two';
		}
		if($scores[3]['home'] != $data[3]['home'] || $scores[3]['guest'] != $data[3]['guest']){
			$process[] = 'three';
		}
		if($scores[4]['home'] != $data[4]['home'] || $scores[4]['guest'] != $data[4]['guest']){
			$process[] = 'four';
		}
		if($scores[5]['home'] != $data[5]['home'] || $scores[5]['guest'] != $data[5]['guest']){
			$process[] = 'uhalf';
		}
		if($scores[6]['home'] != $data[6]['home'] || $scores[6]['guest'] != $data[6]['guest']){
			$process[] = 'dhalf';
		}
		if($scores['all']['home'] != $data['all']['home'] || $scores['all']['guest'] != $data['all']['guest']){
			$process[] = 'all';
		}

		if(!empty($process)){
			//赛事下注单作废 处理
			commonFunction::HandleInvalid($data,$match_id,$match_status,'lq',$process);

			$updatainfo = [
				"inning"=>json_encode($data),
				"manual_result"=>json_encode($data),
				'is_correct'=>1
			];

			\App\Models\Stlqresult::where('match_id', $match_id)->update($updatainfo);

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

			//赛事下所有注单状态都改变时，修改赛事，赛事结果状态
			if(count($process) == count($data)){
				$twoapp = new \App\Models\SportsBasket();
				$twoapp->updatestatus('id',$match_id,['status'=>2,'utime'=>date('Y-m-d H:i:s')]);//修改赛事状态
				$newapp = new \App\Models\Stlqresult();
				$newapp->updatestatus('match_id',$match_id,['status'=>2,'update_time'=>date('Y-m-d H:i:s')]);//修改结果状态
			}

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

		return responseToJson(1);
	}

	//查询赛事结果
	function Matchresult(Req $req){
		$match_id = $req->match_id;
		$newapp = \App\Models\Stlqresult::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,
//		);
		$array =array(
			'lqresult' => json_decode($newapp['manual_result'],true),
			'newapp' => $newapp,
		);
		return $array;
	}

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


	//结算
	function Settlement1(Req $req){
		$match_id = $req->match_id;
		$match = \App\Models\SportsBasket::where('id', $match_id)->first();
		$type = $req->type;
		$process = $req->process;
		if(empty($process)){
			$process = array();
		}

		//赛事比分数据
		$res = \App\Models\Stlqresult::where('match_id', $match_id)->first();
		$scores = json_decode($res['manual_result'],true);

		//结算验证
		if(in_array('one',$process)){
			if(strlen($scores['1']['home'])==0 || strlen($scores['1']['guest'])==0){
				return json_encode(['status'=>6,'msg'=>'没有第一节结果,无法结算第一节']);
			}
		}
		if(in_array('two',$process)){
			if(strlen($scores['2']['home'])==0 || strlen($scores['2']['guest'])==0){
				return json_encode(['status'=>7,'msg'=>'没有第二节结果,无法结算第二节']);
			}
		}
		if(in_array('three',$process)){
			if(strlen($scores['3']['home'])==0 || strlen($scores['3']['guest'])==0){
				return json_encode(['status'=>8,'msg'=>'没有第三节结果,无法结算第三节']);
			}
		}
		if(in_array('four',$process)){
			if(strlen($scores['4']['home'])==0 || strlen($scores['4']['guest'])==0){
				return json_encode(['status'=>9,'msg'=>'没有第四节结果,无法结算第四节']);
			}
		}
		if(in_array('uhalf',$process)){
			if(strlen($scores['5']['home'])==0 || strlen($scores['5']['guest'])==0){
				return json_encode(['status'=>10,'msg'=>'没有上半场结果,无法结算上半场']);
			}
		}
		if(in_array('dhalf',$process)){
			if(strlen($scores['6']['home'])==0 || strlen($scores['6']['guest'])==0){
				return json_encode(['status'=>11,'msg'=>'没有下半场结果,无法结算下半场']);
			}
		}
		if(in_array('all',$process)){
			if(strlen($scores['all']['home'])==0 || strlen($scores['all']['guest'])==0){
				return json_encode(['status'=>12,'msg'=>'没有全场结果,无法结算全场']);
			}
		}

		$token = session('adminInfo.token');
		$notice = \App\Models\Comendnotice::where('match_id', $match_id)->first();

		if(!$notice){
			return json_encode(['status'=>5,'msg'=>'请先核对结果,并提交结果']);
		}
		$noticeid = $notice['id'];
		//查询赛事单式是否有订单(蓝球)
		$newapp = new \App\Models\MoneyBuyMatch();
		$simplex = $newapp->simsettleorder($match_id,$type);
		$str = $newapp->strsettleorder($match_id);

		//获取赛事结算进程下的注单
		$simplex = commonFunction::getOrderData($data = [],$simplex,$type,$process);
		//$str = commonFunction::getOrderData($data = [],$str,$type,$process);

		//获取注单id组成一维数组
		$simplex_ids = array_column($simplex['settle'],'order_id');
		$str_ids = array();
		foreach($str as $key){
			$str_ids[]= $key['order_id'];
		}

		//去重
		$simplex_ids = array_unique($simplex_ids);
		$str_ids = array_unique($str_ids);
//		print_r($simplex_ids);exit;

		//判断赛事下注单输赢
		$datas = array('noticeid' => $noticeid , 'token' => $token);
		$settlementAuto = new \App\Lib\Settlement\SettlementAuto();
		$winfail = $settlementAuto->SubmitSettelement('w',$datas);
		if($winfail == false){
			return json_encode(['status'=>2,'msg'=>'判断输赢错误,请联系管理员!!!']);//输赢错误
		}

		$change_status = 1;
		if($match['status'] == 0 || $match['status'] == 1){
			$change_status = 0;
		}
		$sim = array(
			'token'=>$token,
			'order_ids'=>'', //订单id字符串，用半角都好分隔
			'bettype'=>1, //结算类型  1单式  2串式
			'settype'=>2, //结算次数  1首次  2非首次
			'game_code'=>$type, //赛事类型  zq lq wq bq
			'match_id'=>$match_id,  // 赛事ID
			'change_status'=>$change_status  //是否改状态
		);
		$str = array(
			'token'=>$token,
			'order_ids'=>'', //订单id字符串，用半角都好分隔
			'bettype'=>2, //结算类型  1单式  2串式
			'settype'=>2, //结算次数  1首次  2非首次
			'game_code'=>$type, //赛事类型  zq lq wq bq
			'match_id'=>$match_id,  // 赛事ID
			'change_status'=>$change_status  //是否改状态
		);
		if(count($simplex_ids)>0 || count($str_ids)>0){
			//单式结算
			if(count($simplex_ids)>0 && count($str_ids)==0){
				$sim['order_ids'] = implode(',',$simplex_ids);
				$settlesim = $settlementAuto->SubmitSettelement('s',$sim);
				if($settlesim == false){
					return json_encode(['status'=>3,'msg'=>'单式注单结算有误,请联系管理员!!!']);
				}else{
					return json_encode(['status'=>1,'msg'=>'单式结算成功,没有串式订单']);
				}
			}
			//串式结算
			elseif(count($str_ids)>0 && count($simplex_ids)==0){
				$str['order_ids'] = implode(',',$str_ids);
				$settlestr = $settlementAuto->SubmitSettelement('s',$str);
				if($settlestr == false){
					return json_encode(['status'=>3,'msg'=>'串式注单结算有误,请联系管理员!!!']);
				}else{
					return json_encode(['status'=>1,'msg'=>'串式结算成功,没有单式订单']);
				}
			}
			//既有单式也有串式
			elseif(count($str_ids)>0 && count($simplex_ids)>0){
				$sim['order_ids'] = implode(',',$simplex_ids);
				$str['order_ids'] = implode(',',$str_ids);
				$settlesim = $settlementAuto->SubmitSettelement('s',$sim);
				$settlestr = $settlementAuto->SubmitSettelement('s',$str);
				if($settlesim == true || $settlestr == true){
					return json_encode(['status'=>1,'msg'=>'结算成功']);
				}else{
					return json_encode(['status'=>3,'msg'=>'结算有误,请联系管理员!!!']);
				}
			}
		}else{
			$log = array(
				session('adminInfo.admin_name'),
			);
			OperationLog(session('adminInfo.admin_id'), '蓝球结算', $log);
			if($match['status'] == 0 || $match['status'] == 1){
				return json_encode(['status'=>4,'msg'=>'该赛事进程下没有任何订单']);
			}
			$res = \App\Models\Stlqresult::where ('match_id', $match_id)->update(['status' =>3]);
			$res = \App\Models\SportsBasket::where ('id', $match_id)->update(['status' =>3]);
			return json_encode(['status'=>4,'msg'=>'该赛事没有任何订单,将会结束该赛事!!!']);
		}

	}

    //结算
	function Settlementlq(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->simsettleorder($match_id,'lq'),'order_id');
		$str_ids = array_column($newapp->strsettleorder($match_id),'order_id');

		//去重
		$simplex_ids = array_unique($simplex_ids);
		$str_ids = array_unique($str_ids);

		//判断赛事下注单输赢
		$datas = array('noticeid' => $noticeid , 'token' => $token);
		$settlementAuto = new \App\Lib\Settlement\SettlementAuto();
		$winfail = $settlementAuto->SubmitSettelement('w',$datas);
		if($winfail == false){
			return json_encode(['status'=>2,'msg'=>'判断输赢错误,请联系管理员!!!']);//输赢错误
		}
		$sim = array(
			'token'=>$token,
			'order_ids'=>'', //订单id字符串，用半角都好分隔
			'bettype'=>1, //结算类型  1单式  2串式
			'settype'=>2, //结算次数  1首次  2非首冷饮
			'game_code'=>$type, //赛事类型  zq lq wq bq
			'match_id'=>$match_id,  // 赛事ID
			'change_status'=>1  //是否改状态
		);
		$str = array(
			'token'=>$token,
			'order_ids'=>'', //订单id字符串，用半角都好分隔
			'bettype'=>2, //结算类型  1单式  2串式
			'settype'=>2, //结算次数  1首次  2非首冷饮
			'game_code'=>$type, //赛事类型  zq lq wq bq
			'match_id'=>$match_id,  // 赛事ID
			'change_status'=>1  //是否改状态
		);
		if(count($simplex_ids)>0 || count($str_ids)>0){
			//单式结算
			if(count($simplex_ids)>0 && count($str_ids)==0){
				$sim['order_ids'] = implode(',',$simplex_ids);
				$settlesim = $settlementAuto->SubmitSettelement('s',$sim);
				if($settlesim == false){
					return json_encode(['status'=>3,'msg'=>'单式注单结算有误,请联系管理员!!!']);
				}else{
					return json_encode(['status'=>1,'msg'=>'单式结算成功,没有串式订单']);
				}
			}
			elseif(count($str_ids)>0 && count($simplex_ids)==0){
				$str['order_ids'] = implode(',',$str_ids);
				$settlestr = $settlementAuto->SubmitSettelement('s',$str);
				if($settlestr == false){
					return json_encode(['status'=>3,'msg'=>'串式注单结算有误,请联系管理员!!!']);
				}else{
					return json_encode(['status'=>1,'msg'=>'串式结算成功,没有单式订单']);
				}
			}
			elseif(count($str_ids)>0 && count($simplex_ids)>0){
				$sim['order_ids'] = implode(',',$simplex_ids);
				$str['order_ids'] = implode(',',$str_ids);
				$settlesim = $settlementAuto->SubmitSettelement('s',$sim);
				$settlestr = $settlementAuto->SubmitSettelement('s',$str);
				if($settlesim == true || $settlestr == true){
					return json_encode(['status'=>1,'msg'=>'结算成功']);
				}else{
					return json_encode(['status'=>3,'msg'=>'结算有误,请联系管理员!!!']);
				}
			}
		}else{
			$log = array(
				session('adminInfo.admin_name'),
			);
			OperationLog(session('adminInfo.admin_id'), '篮球结算', $log);
			$res = \App\Models\Stlqresult::where ('match_id', $match_id)->update(['status' =>3]);
			$res = \App\Models\SportsBasket::where ('id', $match_id)->update(['status' =>3]);
			return json_encode(['status'=>4,'msg'=>'该赛事没有任何订单,将会结束该赛事!!!']);
		}
	}

	function info() {
		$page = Request::has('page') ? Request::get('page') : '';
		$list = Request::has('limit') ? Request::get('limit') : 1;
		$home_team = Request::has('home_team') ? Request::get('home_team') : '';
		$sureblurs = Request::has('sureblurs') ? Request::get('sureblurs') : 'off';
		$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' : '';
		$status = Request::has('status') ? Request::get('status') : '';
		$if_order = Request::has('if_order') ? Request::get('if_order') : '';
		$where = array();
		$orwhere = array();
		if (!empty($home_team)) {
			if (empty($sureblurs) || $sureblurs == 'off') {
				$where[] = array('st_lq_result.home_team', 'like', '%' . $home_team . '%');
				$orwhere[] = array('st_lq_result.guest_team', 'like', '%' . $home_team . '%');
			} else {
				if(is_numeric($home_team)){
					$where[] = array('st_lq_result.match_id', '=', $home_team);
                    $orwhere[] = array('st_lq_result.match_id', '=', $home_team);
				}else{
					$where[] = array('st_lq_result.home_team', '=', $home_team);
					$orwhere[] = array('st_lq_result.guest_team', '=', $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_lq_result.start_time', '>', $star_time);
            $orwhere[] = array('st_lq_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_lq_result.start_time', '<', $end_time);
            $orwhere[] = array('st_lq_result.start_time', '<', $end_time);
        }

		if ($status != -1) {
			$where[] = array('st_lq_competition.status', '=', $status);
			$orwhere[] = array('st_lq_competition.status', '=', $status);
		}
		
		$newapp = new \App\Models\Stlqresult();
		$data = $newapp->resultbklist($list, $page, $where, $orwhere,$if_order);
		
		for ($i=0; $i < count($data['data']); $i++) { 
			$home_score = json_decode($data['data'][$i]['home_score'],true);
			$guest_score = json_decode($data['data'][$i]['guest_score'],true);
			$data['data'][$i]['okteamscore'] = $guest_score[1];//第一节客队比分
			$data['data'][$i]['ozteamscore'] = $home_score[1];//第一节主队比分
			$data['data'][$i]['tkteamscore'] = $guest_score[2];//第二节客队比分
			$data['data'][$i]['tzteamscore'] = $home_score[2];//第二节主队比分
			$data['data'][$i]['skteamscore'] = $guest_score[3];//第三节客队比分
			$data['data'][$i]['szteamscore'] = $home_score[3];//第三节主队比分
			$data['data'][$i]['akteamscore'] = $guest_score[4];//第四节客队比分
			$data['data'][$i]['azteamscore'] = $home_score[4];//第四节主队比分

			if(empty($data['data'][$i]['match_score'])){
				$data['data'][$i]['home_scores'] = 0;
				$data['data'][$i]['guest_scores'] = 0;
			}else{
				$scores = explode(':',$data['data'][$i]['match_score']);
				$data['data'][$i]['home_scores'] = $scores[0];
				$data['data'][$i]['guest_scores'] = $scores[1];
			}

		}

		return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total']);
	}

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

		$model = \App\Models\Stlqresult::where('match_id', $match_id)->first();
		$model->update_time = date('Y-m-d H:i:s');
			
		//赛事状态
		$match_status = intval($req->match_status)?intval($req->match_status):0;
		$guestscore =array(
			'1' => intval($req->okteamscore)?intval($req->okteamscore):0,//第一节客队比分
			'2' => intval($req->tkteamscore)?intval($req->tkteamscore):0,//第二节客队比分
			'3' => intval($req->skteamscore)?intval($req->skteamscore):0,//第三节客队比分
			'4' => intval($req->akteamscore)?intval($req->akteamscore):0,//第四节客队比分
		);
		
		$homescore =array(
			'1' => intval($req->ozteamscore)?intval($req->ozteamscore):0,//第一节主队比分
			'2' => intval($req->tzteamscore)?intval($req->tzteamscore):0,//第二节主队比分
			'3' => intval($req->szteamscore)?intval($req->szteamscore):0,//第三节主队比分
			'4' => intval($req->azteamscore)?intval($req->azteamscore):0,//第四节主队比分
		);
		$model->guest_score = json_encode($guestscore);
		$model->home_score = json_encode($homescore);
		$model->is_correct = 1;//追加手动更改标识

		$model->save();

		//更新比分 默认 status
		$status = 2;
		
		//赛事下注单作废 处理
		$data = array_merge($guestscore,$homescore);
		if(in_array(-1,$data)){
			commonFunction::HandleInvalid($data,$match_id,$match_status,'lq');
		}

		/*
		//追加判断比分 如果都== -1，则作废该赛事
		if($guestscore[1] < 0 and $guestscore[2] < 0 and $guestscore[3] < 0 and $guestscore[4] < 0 and $homescore[1] < 0 and $homescore[2] < 0 and $homescore[3] < 0 and $homescore[4] < 0 ){
			//已结算作废赛事处理
			if($match_status == 3){
				$url = 'http://stadmin.bocai108.com:9094/UnSettelement';
				$data_up = [
					'token'=>session('adminInfo.token'),
					'game_code'=>'lq',
					'match_id'=>$match_id,
				];
				$ret_json = commonFunction::https_request($url,$data_up);
				// $ret_json = '{"status":1,"msg":"撤销成功!2019-10-26 16:28:30 取消赛事处理--结束end：game_code= zq  match_id= 40986 \n","data":[]}';

				$ret_arr = json_decode($ret_json,true);
				if($ret_arr['status'] != 1){
					return responseToJson(-20003);
				}
			}
			//赛事下单式注单作废，串关注单下此赛事按平局处理
			$upapp = new \App\Models\SportsNoteList();
			$upapp->delorder($match_id,'lq');
			$status = 4;
		}
		*/

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

		$twoapp = new \App\Models\SportsBasket();
		$twoapp->updatestatus('match_id',$match_id,['status'=>$status,'utime'=>date('Y-m-d H:i:s')]);//修改赛事状态
		$newapp = new \App\Models\Stlqresult();
		$newapp->updatestatus('match_id',$match_id,['status'=>$status,'update_time'=>date('Y-m-d H:i:s')]);//修改结果状态

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

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

		return responseToJson(1); 
	}

	function saislist(){
		$lgid = $_POST['lgid'];//赛事id
		$newstzqcompetition = new \App\Models\SportsBasket();
		$league_data = $newstzqcompetition->allcompetition($lgid);//赛事id

		return $league_data;
	}

	function addoutcome(Req $req) {
		if (!$req->isMethod('post')) {
            $lange = trans('menu');
			$newapp = new \App\Models\BasketLeague();
			$league_data = $newapp->allleague();//联赛id
			return view('admin.sportsbk/addoutcome',['data'=>$league_data]);
		}else{
			$model = new \App\Models\Stlqresult();
			$model->lg_id = trim($req->input('lg_id'));//联赛id
			$model->home_team = trim($req->input('home_team'));
			$model->guest_team = trim($req->input('guest_team'));
			$model->home_rate = trim($req->input('home_rate'));
			$model->guest_rate = trim($req->input('guest_rate'));
			$model->home_score = trim($req->input('home_score'));
			$model->guest_score = trim($req->input('guest_score'));
			$model->all_goal = trim($req->input('all_goal'));
			$model->match_score = trim($req->input('match_score'));
			$model->u_home_score = trim($req->input('u_home_score'));
			$model->u_guest_score = trim($req->input('u_guest_score'));
			$model->update_time = date('Y-m-d h:i:s', time());//更新时间
			$model->match_time = "11:22";//trim($req->input('match_time'));
			$model->tag = trim($req->input('tag'));
			$model->status = trim($req->input('status'));
			$model->match_process = trim($req->input('match_process'));
			$model->match_id = trim($req->input('match_id'));//赛事id

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

		}
	}

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

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

			return view('admin.sportsbk/edit', $data);
		} else {
			$model = \App\Models\Stlqresult::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 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\Stlqresult::whereIn('id', $ids)->delete();
		if (!$rows) {
			return responseToJson(-2003); 
		}
		return responseToJson(1); 
	}

	//获取赛事进程数据
	function getprocess(Req $req){
		$type = $req->type;

		$process = commonFunction::getprocess($type);
		return json_encode($process);
	}

}