<?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 SportsfootController extends Controller {

	function Settlement1(Req $req){
		$match_id = $req->match_id;
		$match = \App\Models\SportsSoccer::where ('id', $match_id)->first();
		$type = $req->type;
		$process = $req->process;
		if(empty($process)){
			$process = array();
		}
		//赛事比分数据
		$res = \App\Models\Stzqresult::where('match_id', $match_id)->first();
		$scores = json_decode($res['manual_result'],true);

		//结算验证
		if(in_array('half_corner',$process)){
			if(strlen($scores['half_corner']['home'])==0 || strlen($scores['half_corner']['guest'])==0){
				return json_encode(['status'=>6,'msg'=>'没有上半场角球结果,无法结算上半场角球']);
			}
		}
		if(in_array('all_corner',$process)){
			if(strlen($scores['all_corner']['home'])==0 || strlen($scores['all_corner']['guest'])==0){
				return json_encode(['status'=>7,'msg'=>'没有全场角球结果,无法结算全场角球']);
			}
		}
		if(in_array('half',$process)){
			if(strlen($scores['half']['home'])==0 || strlen($scores['half']['guest'])==0){
				return json_encode(['status'=>8,'msg'=>'没有上半场结果,无法结算上半场']);
			}
		}
		if(in_array('all',$process)){
			if(strlen($scores['all']['home'])==0 || strlen($scores['all']['guest'])==0){
				return json_encode(['status'=>9,'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\Stzqresult::where ('match_id', $match_id)->update(['status' =>3]);
			$res = \App\Models\SportsSoccer::where ('id', $match_id)->update(['status' =>3]);
            return json_encode(['status'=>4,'msg'=>'该赛事没有任何订单,将会结束该赛事!!!']);
		}
		
	}

	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();

		if(!$notice){
			return json_encode(['status'=>5,'msg'=>'请先核对结果,并提交结果']);
		}
		$noticeid = $notice['id'];
		//查询赛事单式是否有订单(足球)
		$newapp = new \App\Models\MoneyBuyMatch();
		$simplex_ids = array_column($newapp->simsettleorder($match_id,'zq'),'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\Stzqresult::where ('match_id', $match_id)->update(['status' =>3]);
			$res = \App\Models\SportsSoccer::where ('id', $match_id)->update(['status' =>3]);
			return json_encode(['status'=>4,'msg'=>'该赛事没有任何订单,将会结束该赛事!!!']);
		}

	}

	//添加危险球列表
	function addwarn(Req $req){
		$match_id = $req->match_id;
		$warn = \App\Models\Stzqresult::where('match_id', $match_id)->select("warn_more")->first();
		$warnmore = json_decode($warn['warn_more'],true);

		$sousuo = $req->sousuo?$req->sousuo:'';
		if($sousuo){
			$shuzu = array();
			for ($i=0; $i < count($warnmore); $i++) { 
			    if($warnmore[$i]['rtype']==$sousuo){
			        $shuzu[$i]['timei'] = $warnmore[$i]['timei'];
			        $shuzu[$i]['rtype'] = $warnmore[$i]['rtype'];
					$shuzu[$i]['timep'] = $warnmore[$i]['timep'];
			    }
			}
			$shuzu = array_values($shuzu);
			$warnmore = $shuzu;
			// $warnmore[0]['timei'] = 10000;
		}
		
		if($warnmore[0]['timei']!="1970-1-1 0:0:1"){
			$request['warnmore'] = $warnmore;
			// $request['warnmore'][0]['rtype'] = $sousuo;1
		}else{
			$request['warnmore'] = '';
		}
		
		$request['match_id'] = $match_id;
		$request['sousuo'] = $sousuo;
		
		return view('admin.sportsfoot/addwarn', $request);
	}

	//获取指定赛事危险球数据
	function getWarnData(Req $req){
		$match_id = $req->match_id;
		$warnonlys = \App\Models\Stzqresult::where('match_id', $match_id)->select("warn_more","start_time")->first();
		$warn_more = json_decode($warnonlys['warn_more'],true);

		if(!empty($warn_more)){
			$data = [];
			foreach($warn_more as $k=>$v){
				$v['id'] =$k+1;
				$data[$k] = $v;
			}
		}

		if($data[0]['timei']=="1970-1-1 0:0:1"){
			$data = [];
		}

		return \App\Lib\DataTable\DataTable::init()->toJson($data);
	}

	//危险球查询
	function warnresult(Req $req){
		$match_id = $req->match_id;
		$wid = $req->wid;
		$typenum = $req->typenum;
		$warnonlys = \App\Models\Stzqresult::where('match_id', $match_id)->select("warn_more","start_time")->first();

		$warn_data = json_decode($warnonlys['warn_more'],true);
		if($typenum == 10000){ //添加危险球时，默认出现时间为赛事开始时间
			$warn_data[0] =[
				'timei' =>$warnonlys['start_time'],
				'rtype' =>0,
				'timep' =>90
			];
		}

		$warno = array(
			'warn_more' => $warn_data,
			'starttime' => $warnonlys['start_time'],
			'endtime'=> date("Y-m-d H:i:s", strtotime("+2 hour",strtotime($warnonlys['start_time']))),//$warnonlys['start_time']
		);
		

		return $warno;
	}

	//添加编辑危险球
	function addwarnonly(Req $req){


		//编辑对象值
		$wid = ($req->wid);
		//赛事id
		$matchid = $req->match_id;
		/*
		//出现危险球的分钟数
		$time_i = $req->time_i;
		//出现危险球的秒数
		$time_s = $req->time_s;
		//危险球审核有效时间 秒
		*/
		$timei = $req->time_i;

		$timep = $req->time_p;
		//危险球类型
		$rtype = $req->warn_type;
		//验证是否是首次添加危险球
		$typenum = $req->type_num;


		if(empty($matchid)  || empty($timep) || empty($rtype))  return json_encode(['status'=>2,'msg'=>'设置数据异常']);
		$model = \App\Models\Stzqresult::where('match_id', $matchid)->select("warn_more","start_time","status")->first()->toArray();
		// if($model['status'] != 2) return json_encode(['status'=>3,'msg'=>'赛事未结束，不能设置危险球']);

		/*
		//赛事开赛时间
		$match_time = $model['start_time'];
		//危险球出现进行时间 秒
		$warn_time_s = ($time_i*60)+$time_s;
		//危险球出现时间  == 开赛时间+进行时间 秒
		$timei = date('Y-m-d H:i:s',strtotime($match_time)+$warn_time_s);
		*/

		//该赛事的单式注单
		$orders = array();
		$otherorders = array();
		$account_identitys = array();
		$order_ids = array();
		$order = \App\Models\SportsNoteList::where('match_id',$matchid)->get();
		if(!empty($order)){
			for ($c=0; $c < count($order); $c++){
				if(strtotime($timei) >= strtotime($order[$c]['money_time']) && strtotime($timei)-$timep <= strtotime($order[$c]['money_time'])){
					$orders[] = $order[$c];
					$account_identitys[] = $order[$c]['account_identity'];
					$order_ids[] = $order[$c]['order_id'];
				}else{
					$otherorders[] = $order[$c]['id'];
				}
			}
		}

		//危险球范围外的注单自动审核通过
		//return $otherorders;
		if(!empty($otherorders)){
			\App\Models\SportsNoteList::wherein('id', $otherorders)->update(['roll_ratify' => '1']);
		}

		//return $account_identitys;

		$sel = json_decode($model['warn_more'],true);
		$addru = array(
			array(
	        	'timei'=>$timei,
				'timep'=>$timep,
	        	'rtype'=>$rtype,
	        ),
        );

		if($typenum==10000){
		if($sel[0]['timei']=="1970-1-1 0:0:1"){
			//首次添加
			$res = \App\Models\Stzqresult::where ('match_id', $matchid)->update(['warn_more' => json_encode($addru,JSON_UNESCAPED_UNICODE)]);
		}else{
			//再次添加
			$upnum = array_merge_recursive($sel,$addru);
			$res = \App\Models\Stzqresult::where ('match_id', $matchid)->update(['warn_more' => json_encode($upnum,JSON_UNESCAPED_UNICODE)]);
		}
		}else{
		//编辑
		for ($i=0; $i < count($sel); $i++) {
			$sel[$wid]['timei'] = $timei;
			$sel[$wid]['timep'] = $timep;
			$sel[$wid]['rtype'] = $rtype;
		}
		$res = \App\Models\Stzqresult::where ('match_id', $matchid)->update(['warn_more' => json_encode($sel,JSON_UNESCAPED_UNICODE)]);
		}

		//用戶账户金额
		$account_money = \App\Models\Account_detailed::wherein('account_identity',$account_identitys)->get();
		//反水
		$water_return_money = \App\Models\Money_details::wherein('trade_id',$order_ids)->where('trade_type', '7')->get();

		if(!empty($orders)){
			for($i=0;$i<count($orders);$i++){
				for($a=0;$a<count($account_money);$a++){
					if($orders[$i]['account_identity'] == $account_money[$a]['account_identity']){
						$available_cash = $account_money[$a]['available_cash'];
					}
				}
				for($b=0;$b<count($water_return_money);$b++){
					if($orders[$i]['order_id'] == $water_return_money[$b]['trade_id']){
						$water_return = $water_return_money[$b]['money'];
					} else {
						$water_return = 0;
					}
				}
				$new_available_cash = $available_cash + $orders[$i]->money - $orders[$i]->gain_money - $water_return;

				$models = new \App\Models\Money_details();
				$models->info_identity = UUID();
				$models->trade_id = $orders[$i]->order_id;
				$models->account_name = $orders[$i]->account_name;
				$models->account_identity = $orders[$i]->account_identity;
				$models->money = abs($orders[$i]->money - $orders[$i]->gain_money - $water_return);
				$models->money_time = date("Y-m-d H:i:s", time());
				if ($new_available_cash > $available_cash) {
					$models->money_type = '1';
				} else {
					$models->money_type = '2';
				}
				$models->money_cash = $new_available_cash;
				$models->trade_type = '25';
				$models->trade_desc = '单式注单审核不通过回款';
				$models->status = '1';
				try {
					DB::beginTransaction();//开启事务
					\App\Models\SportsNoteList::where('id', $orders[$i]['id'])->update(['roll_ratify' => '-1','status' => '2']);
					\App\Models\Account_detailed::where('account_identity', $orders[$i]->account_identity)->update(['available_cash' => $new_available_cash, 'cash' => $new_available_cash]);
					$models->save();

					DB::commit();//提交
				} catch (Exception $e) {
					DB::rollback();//回滚
				}

			}
		}
		
		return responseToJson(1);
	}
	//弃用
	function addwarnonly__(Req $req){
		$matchid = $req->matchid;
		$wid = $req->wid;//编辑对象值
		$timei = $req->timei?$req->timei:"1970-11-1 0:0:1";
		$timep = $req->timep?$req->timep:"90";
		$rtype = $req->warntype?$req->warntype:0;
		$typenum = $req->typenum;
		$model = \App\Models\Stzqresult::where('match_id', $matchid)->select("warn_more","start_time")->first()->toArray();

		//该赛事的单式注单
		$orders = array();
		$otherorders = array();
		$account_identitys = array();
		$order_ids = array();
		$order = \App\Models\SportsNoteList::where('match_id',$matchid)->get();
		if(!empty($order)){
			for ($c=0; $c < count($order); $c++){
				if(strtotime($timei) >= strtotime($order[$c]['money_time']) && strtotime($timei)-$timep <= strtotime($order[$c]['money_time'])){
					$orders[] = $order[$c];
					$account_identitys[] = $order[$c]['account_identity'];
					$order_ids[] = $order[$c]['order_id'];
				}else{
					$otherorders[] = $order[$c]['id'];
				}
			}
		}

		//危险球范围外的注单自动审核通过
		//return $otherorders;
		if(!empty($otherorders)){
			\App\Models\SportsNoteList::wherein('id', $otherorders)->update(['roll_ratify' => '1']);
		}

		//return $account_identitys;

		$sel = json_decode($model['warn_more'],true);
		$addru = array(
			array(
	        	'timei'=>$timei,
				'timep'=>$timep,
	        	'rtype'=>$rtype,
	        ),
        );
		$only =$model['start_time'];
		$t = strtotime($only);
		$tt = date('Y-m-d H:i:s', $t+1*3*60*60);
		//timei']!="1970-1-1 0:0:1"
		if($only<$timei && $timei<$tt){
			if($typenum==10000){
				if($sel[0]['timei']=="1970-1-1 0:0:1"){
					//首次添加
					$res = \App\Models\Stzqresult::where ('match_id', $matchid)->update(['warn_more' => json_encode($addru,JSON_UNESCAPED_UNICODE)]);
				}else{
					//再次添加
					$upnum = array_merge_recursive($sel,$addru);
					$res = \App\Models\Stzqresult::where ('match_id', $matchid)->update(['warn_more' => json_encode($upnum,JSON_UNESCAPED_UNICODE)]);
				}
			}else{
				//编辑
				for ($i=0; $i < count($sel); $i++) {
					$sel[$wid]['timei'] = $timei;
					$sel[$wid]['timep'] = $timep;
					$sel[$wid]['rtype'] = $rtype;
				}
				$res = \App\Models\Stzqresult::where ('match_id', $matchid)->update(['warn_more' => json_encode($sel,JSON_UNESCAPED_UNICODE)]);
			}

			//用戶账户金额
			$account_money = \App\Models\Account_detailed::wherein('account_identity',$account_identitys)->get();
			//反水
			$water_return_money = \App\Models\Money_details::wherein('trade_id',$order_ids)->where('trade_type', '7')->get();

			//return $water_return_money;
			if(!empty($orders)){
				for($i=0;$i<count($orders);$i++){
					for($a=0;$a<count($account_money);$a++){
						if($orders[$i]['account_identity'] == $account_money[$a]['account_identity']){
							$available_cash = $account_money[$a]['available_cash'];
						}
					}
					for($b=0;$b<count($water_return_money);$b++){
						if($orders[$i]['order_id'] == $water_return_money[$b]['trade_id']){
							$water_return = $water_return_money[$b]['money'];
						} else {
							$water_return = 0;
						}
					}
					$new_available_cash = $available_cash + $orders[$i]->money - $orders[$i]->gain_money - $water_return;

					$models = new \App\Models\Money_details();
					$models->info_identity = UUID();
					$models->trade_id = $orders[$i]->order_id;
					$models->account_name = $orders[$i]->account_name;
					$models->account_identity = $orders[$i]->account_identity;
					$models->money = abs($orders[$i]->money - $orders[$i]->gain_money - $water_return);
					$models->money_time = date("Y-m-d H:i:s", time());
					if ($new_available_cash > $available_cash) {
						$models->money_type = '1';
					} else {
						$models->money_type = '2';
					}
					$models->money_cash = $new_available_cash;
					$models->trade_type = '25';
					$models->trade_desc = '单式注单审核不通过回款';
					$models->status = '1';
					try {
						DB::beginTransaction();//开启事务
						\App\Models\SportsNoteList::where('id', $orders[$i]['id'])->update(['roll_ratify' => '-1','status' => '2']);
						\App\Models\Account_detailed::where('account_identity', $orders[$i]->account_identity)->update(['available_cash' => $new_available_cash, 'cash' => $new_available_cash]);
						$models->save();

						DB::commit();//提交
					} catch (Exception $e) {
						DB::rollback();//回滚
					}

				}
			}

		}else{
			return json_encode(['status'=>2,'msg'=>'请设置正确时间']);
		}
		
		return responseToJson(1);
	}

	//足球结果列表 1
	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['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');
        $newapp = new \App\Models\SoccerLeague();
		$data = $newapp->allleague();
        $request['league'] = $data;//联赛id
        $request['token'] = session('adminInfo.token');//token 变量

        $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' => 155));
        $dt->addColsFields('home_team', array('templet' => '#userdetail', 'sort' => false, 'width' => 90));
		$dt->addColsFields('guest_team', array('templet' => '#userdetail', 'sort' => false, 'width' => 90));
		$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('sort' => false, 'width' => 210));
		$dt->addColsFields('match_score', array('templet' => '#match_score', 'sort' => false, 'width' => 180));
        $dt->addColsFields('statusmatch', array('templet' => '#statusmatch', 'sort' => false, 'width' => 100,'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));1
        $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();
		$match = \App\Models\SportsSoccer::where('id', $match_id)->first();
		$match_status = $match['status'];
		$data = array(
			//上半场角球
			"half_corner" => array(
				'home' => strlen($req->homehalfcorner)?$req->homehalfcorner:'',
				'guest' => strlen($req->guesthalfcorner)?$req->guesthalfcorner:'',
			),
			//全场角球
			"all_corner" => array(
				'home' => strlen($req->homeallcorner)?$req->homeallcorner:'',
				'guest' => strlen($req->guestallcorner)?$req->guestallcorner:'',
			),
			//上半场罚牌
			"half_penalty" => array(
				'home' => strlen($req->homehalfcard)?$req->homehalfcard:'',
				'guest' => strlen($req->guesthalfcard)?$req->guesthalfcard:'',
			),
			//全场罚牌
			"all_penalty" => array(
				'home' => strlen($req->homeallcard)?$req->homeallcard:'',
				'guest' => strlen($req->guestallcard)?$req->guestallcard:'',
			),
			//首进球时间
			"first_score" => array(
				'time' => strlen($req->onescoretime)?$req->onescoretime:'',
			),

			//上半场比分
			"half" => array(
				'home' => strlen($req->homehalf)?$req->homehalf:'',
				'guest' => strlen($req->guesthalf)?$req->guesthalf:'',
			),
			//全场比分
			"all" => array(
				'home' => strlen($req->homeall)>0?$req->homeall:'',
				'guest' => strlen($req->guestall)>0?$req->guestall:'',
			),
		);

		//修改足球比分前的比分数据
		$res = \App\Models\Stzqresult::where('match_id', $match_id)->first();
		$scores = json_decode($res['manual_result'],true);
		$process = array();//进程
		//主队上半场角球
		if($scores['half_corner']['home'] != $data['half_corner']['home']){
			$process[] = 'half_corner_home';
		}
		//客队上半场角球
		if($scores['half_corner']['guest'] != $data['half_corner']['guest']){
			$process[] = 'half_corner_guest';
		}
		//主队全场角球
		if($scores['all_corner']['home'] != $data['all_corner']['home']){
			$process[] = 'all_corner_home';
		}
		//客队全场角球
		if($scores['all_corner']['guest'] != $data['all_corner']['guest']){
			$process[] = 'all_corner_guest';
		}
		//主队上半场罚牌
		if($scores['half_penalty']['home'] != $data['half_penalty']['home']){
			$process[] = 'half_penalty_home';
		}
		//客队上半场罚牌
		if($scores['half_penalty']['guest'] != $data['half_penalty']['guest']){
			$process[] = 'half_penalty_guest';
		}
		//主队全场罚牌
		if($scores['all_penalty']['home'] != $data['all_penalty']['home']){
			$process[] = 'all_penalty_home';
		}
		//客队全场罚牌
		if($scores['all_penalty']['guest'] != $data['all_penalty']['guest']){
			$process[] = 'all_penalty_guest';
		}

		if($scores['all']['home'] != $data['all']['home'] || $scores['all']['guest'] != $data['all']['guest']){
			$process[] = 'all';
		}
		if($scores['half']['home'] != $data['half']['home'] || $scores['half']['guest'] != $data['half']['guest']){
			$process[] = 'half';
		}

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

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

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

			$update = $this->addcomendnotice($match_id);

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

			//添加赛事结果记录
			$lastLog = \App\Models\Stzqresultlog::where([
				['match_id', $match_id],
				['type', 1]
			])->orderBy('id', 'desc')->first();
			if(empty($lastLog) || $lastLog['manual_result'] != json_encode($data)){
				\App\Models\Stzqresultlog::insert([
					'match_id' => $match_id,
					'manual_result' => 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\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),
			'first_score' => json_decode($newapp['first_score'],true),
			'manual_result' => json_decode($newapp['manual_result'],true),
			'newapp' => $newapp,
		);
		return $array;
	}

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

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

	//作废
	function revokeft(Req $req){
		$iszf = $req->iszf?$req->iszf:'';//赛事id
		if(intval($iszf)){
			$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]);
					}
				}
			}
			for ($ii=0; $ii < count($ids); $ii++) { 
				$model = \App\Models\Stzqresult::where('match_id', $ids[$ii])->first();
				$model->status = 4;
				$model->save();
				$ssid = $model['match_id'];//赛事id

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

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

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

		        //单式撤单返现
//		        $newapp = new \App\Models\MoneyBuyMatch();
//				$all = $newapp->allsimplexorder($ssid,'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($ssid),'order_id');
//		        $csapp = new \App\Models\MoneyBuyStr();
//		        $csapp->updatestatus($str_ids);//var_dump($ss);die;
//		        //修改money_buy_match 投注结果result=2为平
//		        $newapp->updatast($ssid);
			}
			return responseToJson(1);
		}else{
			$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('id', $match_id)->first();
			if($smodel){
				$smodel->status = 4;
				$smodel->save();
			}

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

//			$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') : '';
		$if_order = Request::has('if_order') ? Request::get('if_order') : '';
        $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' : '';

		$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 {
				if(is_numeric($home_team)){
					$where[] = array('st_zq_result.match_id', '=', $home_team);
                    $orwhere[] = array('st_zq_result.match_id', '=', $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_competition.status', '=', $status);
			$orwhere[] = array('st_zq_competition.status', '=', $status);
		}

        if (!empty($star_time) and empty($home_team)) {
            $star_time = date('Y-m-d H:i:s', strtotime($star_time));
            $where[] = array('st_zq_result.start_time', '>', $star_time);
            $orwhere[] = array('st_zq_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_zq_result.start_time', '<', $end_time);
            $orwhere[] = array('st_zq_result.start_time', '<', $end_time);
        }

        $newapp = new \App\Models\Stzqresult();
        $data = $newapp->resultlist($list, $page, $where, $orwhere,$if_order);
        
        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)]));
        	//添加足球比赛结果记录表
        	\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]);
				}
			}
		}
		
		$rows = \App\Models\Stzqresult::whereIn('id', $ids)->delete();
		if (!$rows) {
			return responseToJson(-2003); 
		}
		return responseToJson(1); 
	}

	
	/**
	 * 更新赛事比分
	 * 追加 赛事及所属注单作废处理
	 */
	function updatenum(Req $req){
		$match_id = $req->match_id;
		$newapp = new \App\Models\Stzqresult();
		
		//赛事状态
		$match_status = intval($req->match_status)?intval($req->match_status):0;

		$data['u_home_score'] = intval($req->u_home_score)?intval($req->u_home_score):0;
		$data['u_guest_score'] = intval($req->u_guest_score)?intval($req->u_guest_score):0;
		$data['home_score'] = intval($req->home_score)?intval($req->home_score):0;
		$data['guest_score'] = intval($req->guest_score)?intval($req->guest_score):0;
		$data['is_correct'] = 1;//追加手动更改标识

		//更新比分 默认 status
		$status = 2;

		//赛事下注单作废 处理
		if(in_array(-1,$data)){
			commonFunction::HandleInvalid($data,$match_id,$match_status,'zq');
			// $this->HandleInvalid($data,$match_id,$match_status,'zq');
		}

		$newapp->updateInfo($data,$match_id);//联赛id
	
		$newapp->totalgoal($match_id);
		$update = $this->addcomendnotice($match_id);

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

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

        if(empty($lastLog) || !(
                $lastLog['u_home_score'] == $data['u_home_score']
                && $lastLog['u_guest_score'] == $data['u_guest_score']
                && $lastLog['home_score'] == $data['home_score']
                && $lastLog['guest_score'] == $data['guest_score']
            )){
            $logData = $data;
            unset($logData['is_correct']);
            $logData['type'] = 2;
            $logData['match_id'] = $match_id;
            $logData['user_id'] = session('adminInfo.admin_id');
            $logData['create_at'] = now();
            \App\Models\Stzqresultlog::insert($logData);
        }

		return responseToJson(1);
	}

	/**
	 * 赛事下注单作废处理
	 * 弃用 保留备份
	 */
	function HandleInvalid($data=[],$match_id='',$match_status='',$game_code=''){
		//===作废处理===
		$moneyBuyMatch = new \App\Models\MoneyBuyMatch();

		//获取赛事下所有单式注单
		$select = ['money_buy_simplex.order_id', 'money_buy_simplex.match_id', 'money_buy_simplex.account_identity', 'money_buy_simplex.account_name','money_buy_simplex.money', 'money_buy_simplex.gain_money','money_buy_match.odds_code','st_odds_code.odds_name'];		
		//obj
		$match_order_sim_obj = $moneyBuyMatch->allsimplexorder($match_id,$game_code,$select);

		//获取赛事下所有串式注单
		$select = ['money_buy_str.order_id', 'money_buy_match.match_id', 'money_buy_str.account_identity', 'money_buy_str.account_name','money_buy_str.money', 'money_buy_str.gain_money','st_odds_code.odds_name','money_buy_match.odds_code'];		
		//obj
		$match_order_str_obj = $moneyBuyMatch->allstrorder($match_id,$game_code,$select);

		//如果赛事下有 单式 注单
		if(!empty($match_order_sim_obj)){
			//获取单式注单中 待处理注单
			$oddsData_sim = $this->getOrderData($data,$match_order_sim_obj,$game_code);
		}

		//如果赛事下有 串式 注单
		if(!empty($match_order_str_obj)){
			//获取串式注单中 待处理注单
			$oddsData_str = $this->getOrderData($data,$match_order_str_obj,$game_code);
		}

		//如果是已结算赛事 
		if($match_status == 3){
			//合并上半场/全场 待处理 单式+串式订单
			$oddsData = array_merge($oddsData_sim,$oddsData_str);
			//去重
			$oddsData = commonFunction::uniquArrV2($oddsData,'order_id');

			$url = 'http://stadmin.bocai108.com:9094/UnsetOneOrder';
			$data_up = [
				'token'=>session('adminInfo.token'),
				'game_code'=>$game_code,
				'match_id'=>$match_id,
			];

			//返回请求状态码
			$set_status = [];
			foreach($oddsData as $k=>$v){
				$data_up['order_id'] = $v['order_id'];
				$ret_json = commonFunction::https_request($url,$data_up);
				$ret_arr = json_decode($ret_json,true);
				$set_status[] = $ret_arr['status'];
			}
			if(in_array(0,$set_status)){
				return responseToJson(-20003);
			}
		}else{
			//未结算赛事 处理 下单式注单作废，串关注单下此赛事按平局处理
			$oddsData_str = $oddsData_str->toArray();
			$upapp = new \App\Models\SportsNoteList();
			$upapp->delorder($match_id,$game_code,$match_order_sim_obj,$oddsData_str);
		}
		//=== end ===
	}
	/**
	 * 获取赛事下 符合条件 待处理注单
	 * 弃用 保留备份
	 */
	function getOrderData($data,$match_order,$game_code){
		//足球 获取 上半场/全场
		if($game_code == 'zq'){
			// 获取上半场作废 需处理 单式注单
			$matchOdds_h = [];
			if($data['u_home_score'] == -1 and $data['u_guest_score'] == -1){
				foreach($match_order as $k=>$v){
					$tmparray = explode('上半场',$v->odds_name);
					if(count($tmparray) > 1){
						$matchOdds_h[] = $v;
					}
				}
			}
			//获取全场作废 需处理 单式注单
			$matchOdds_f = [];
			if($data['home_score'] == -1 and $data['guest_score'] == -1){
				foreach($match_order as $k=>$v){
					$tmparray = explode('全场',$v->odds_name);
					if(count($tmparray) > 1){
						$matchOdds_f[] = $v;
					}
				}
			}

			$orderData = array_merge($matchOdds_h,$matchOdds_f);
		}
		
		return $orderData;
	}
 		
	//添加赛事结束纪录
	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();
		}
	}

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

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

	
}