<?php
/**
 * Created by PhpStorm.
 * User: Jonlin
 * Date: 2019/4/9
 * Time: 9:11
 */

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\Lib\Settlement\SettlementWinFail;
use App\Models;
use Request;

/**
 *
 */
class CheckRollingController extends Controller
{

    public function notelist(Req $req)
    {
        $request['name_chinese'] = isset($req->name_chinese) ? trim($req->name_chinese) : null;
        $request['sureblurs'] = isset($req->sureblurs) ? $req->sureblurs : 'on';
        $request['account'] = isset($req->account) ? trim($req->account) : null;
        $request['star_time'] = isset($req->star_time) ? trim($req->star_time) : null;
        $request['end_time'] = isset($req->end_time) ? trim($req->end_time) : null;
        $request['order_id'] = isset($req->order_id) ? trim($req->order_id) : null;
        $request['match_id'] = isset($req->match_id) ? trim($req->match_id) : null;
        $request['status'] = isset($req->status) ? trim($req->status) : '-1';
        $request['order_status'] = isset($req->order_status) ? trim($req->order_status) : '-1';
        $request['type'] = isset($req->type) ? trim($req->type) : 'zq';
        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/CheckRolling/getinfo');
        $dt->setLang('sportsnotelist');
        //$dt->addColsFields('id', array('templet' => '#userdetail', 'sort' => true, 'width' => 80));
        $dt->addColsFields('match_id_order', array('sort' => true, 'width' => 200));
        $dt->addColsFields('league', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
        $dt->addColsFields('home_guest', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
        $dt->addColsFields('content', array('templet' => '#userdetail', 'sort' => false, 'width' => 250));
        $dt->addColsFields('money', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
        $dt->addColsFields('water_return', array('templet' => '#userdetail', 'sort' => false, 'width' => 70));
        $dt->addColsFields('prize_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
        $dt->addColsFields('result', array('templet' => '#userdetail', 'sort' => false, 'width' => 70));
        $dt->addColsFields('money_match_time', array('templet' => '#userdetail', 'sort' => false, 'width' => 200));
        $dt->addColsFields('order_status', array('sort' => false, 'width' => 80));
        $dt->addColsFields('account_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 110));
        $dt->addColsFields('game_status', array('templet' => '#game_status', 'sort' => false, 'width' => 90));
        //$arr[] = 'view';
//        if (checkRriv('/admin/CheckRolling/edit')) {
//            $arr[] = 'edit';
//        }
//        $dt->setToolBar($arr, array('width' => 70));
        $dt->enableCheckBox();//var_dump($request['type']);
        return view('sports/sports_notelist', $dt->render($request));
    }

    //修改冠军单订单结果
    function orderupgj(Req $req)
    {
        $id = $req->id;//37
        $orderid = $req->order;//S20190916094723915270970
        if (intval($id) < 1) {
            return -1;
        }

        $data = \App\Models\SoccerLeague::where('id', $id)->first();

        $odds_code = \App\Models\SoccerOdds::where('lg_id', $id)->where('type', 1)->where('odds_code', '!=', '')->select('odds_code')->distinct()->get()->toArray();//赔率表

        for ($i = 0; $i < count($odds_code); $i++) {
            $allteam[] = \App\Models\SoccerOdds::where('odds_code', $odds_code[$i]['odds_code'])->where('lg_id', $id)->where('type', 1)->select('team')->distinct()->get()->toArray();
        }

        $data = $data->toArray();
        $isdisplay = \App\Models\Stwqleagueresult::where(['lg_id' => $id, 'status' => 1])->select("game_name")->distinct()->get()->toArray();
        $idisplay = array_column($isdisplay, 'game_name');
        $displays = implode(",", $idisplay);//转换成字符串

        //新增纪录
        foreach ($odds_code as $k => $v) {
            foreach ($allteam[$k] as $kk => $vv) {
                $name = $v['odds_code'];
                $isteam = $allteam[$k][$kk]['team'];
                $res = \App\Models\Stwqleagueresult::where(['lg_id' => $id, 'game_name' => $name, 'result' => $isteam])->first();

                $addresult = [
                    'lg_id' => $id,
                    'game_name' => $name,
                    'result' => $isteam,
                    'ctime' => date('Y-m-d H:i:s', time()),
                    'status' => 0,
                    'updated_at' => date('Y-m-d H:i:s', time()),
                ];

                if (empty($res)) {
                    \App\Models\Stwqleagueresult::insert($addresult);
                }

            }
        }
        $orderjg = \App\Models\SportsNoteList::where(['order_id' => $orderid])->select("single_result")->first();
        $orderjg = json_decode($orderjg['single_result'], true);

        $data['allteam'] = $allteam;
        $data['odds_code'] = $odds_code;
        $data['displays'] = $displays;
        $data['isdisplay'] = $isdisplay;
        $data['orderjg'] = $orderjg;
        $data['orderid'] = $orderid;
        $data['lg_id'] = $id;

        return view('sports/orderupgj', $data);
    }

    //修改冠军单订单结果提交
    function ajaxtj(Req $req)
    {
        $isstatus = $req->isstatus;//更新
        $order = $req->order;

        if ($isstatus) {
            $gjresult = array(
                'lg_id' => $req->lg_id ? $req->lg_id : '',
                'game_name' => $req->odds_code ? $req->odds_code : '',
                'result' => $req->team ? $req->team : '',
                'updatetime' => date("Y-m-d H:i:s", time()),
            );
        } else {
            $gjresult = array(
                'lg_id' => '',
                'game_name' => '',
                'result' => '',
            );
        }

        \App\Models\SportsNoteList::where(['order_id' => $order])->update(['single_result' => json_encode($gjresult, JSON_UNESCAPED_UNICODE)]);

        return responseToJson(1);
    }

    function info()
    {
        $page = Request::has('page') ? Request::get('page') : '';
        $list = Request::has('limit') ? Request::get('limit') : 10;
        $account = Request::get('account') ? Request::get('account') : '';
        $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' : '';
        $order_id = Request::get('order_id') ? Request::get('order_id') : '';
        $match_id = Request::get('match_id') ? Request::get('match_id') : '';
        $status = Request::has('status') ? Request::get('status') : '';
        $order_status = Request::has('order_status') ? Request::get('order_status') : '';
        $sureblur = Request::has('sureblurs') ? Request::get('sureblurs') : 'off';
        $type = Request::has('type') ? Request::get('type') : 'zq';
        $where = array();
        //注单状态为投注
        $where[] = array('money_buy_simplex.status', '=', 1);
        //滚球审核状态为为审核
        $where[] = array('money_buy_simplex.roll_ratify', '=', 2);
        if (!empty($account)) {
            if (empty($sureblur) || $sureblur == 'off') {
                $where[] = array('money_buy_simplex.account_name', 'like', '%' . $account . '%');
            } else {
                $where[] = array('money_buy_simplex.account_name', '=', $account);
            }
        }
        if (!empty($star_time)) {
            if (!empty($end_time)) {
                $where[] = array('money_buy_simplex.money_time', '>', $star_time);
                $where[] = array('money_buy_simplex.money_time', '<', $end_time);
            } else {
                $where[] = array('money_buy_simplex.money_time', '>', $star_time);
            }
        } else if (empty($star_time)) {
            if (!empty($end_time)) {

                $where[] = array('money_buy_simplex.money_time', '<', $end_time);
            }
        }
        if (!empty($order_id)) {
            $where[] = array('money_buy_simplex.order_id', $order_id);
        }
        if (!empty($match_id)) {
            $where[] = array('money_buy_simplex.match_id', $match_id);
        }
        $where[] = array('money_buy_simplex.game_code', $type);
        $newapp = new \App\Models\SportsNoteList();
        $data = $newapp->checkinfo($list, $page, $where, $type);
        //$alldata = $newapp->join('money_buy_match','money_buy_match.order_id','=','money_buy_simplex.order_id')->where('money_buy_match.bet_type',1)->where('money_buy_match.is_rolling',1)->where('money_buy_match.game_code',$type)->distinct('money_buy_match.order_id')->count('money_buy_match.order_id');

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

    public function search(Req $req)
    {
        $request['name_chinese'] = isset($req->name_chinese) ? trim($req->name_chinese) : null;
        $request['sureblurs'] = isset($req->sureblurs) ? $req->sureblurs : 'on';
        $request['account'] = isset($req->account) ? trim($req->account) : null;
        $request['star_time'] = isset($req->star_time) ? trim($req->star_time) : null;
        $request['end_time'] = isset($req->end_time) ? trim($req->end_time) : null;
        $request['order_id'] = isset($req->order_id) ? trim($req->order_id) : null;
        $request['match_id'] = isset($req->match_id) ? trim($req->match_id) : null;
        $request['status'] = isset($req->status) ? trim($req->status) : '-1';
        $request['order_status'] = isset($req->order_status) ? trim($req->order_status) : '-1';
        $request['type'] = isset($req->type) ? trim($req->type) : 'zq';
        $request['check'] = 'check';
        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/CheckRolling/info');
        $dt->setLang('sportsnotelist');
        //$dt->addColsFields('id', array('templet' => '#userdetail', 'sort' => true, 'width' => 80));
        $dt->addColsFields('match_id_order', array('sort' => true, 'width' => 200));
        $dt->addColsFields('league', array('templet' => '#userdetail', 'sort' => false, 'width' => 100));
        $dt->addColsFields('home_guest', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
        $dt->addColsFields('content', array('templet' => '#userdetail', 'sort' => false, 'width' => 250));
        $dt->addColsFields('money', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
        $dt->addColsFields('water_return', array('templet' => '#userdetail', 'sort' => false, 'width' => 70));
        $dt->addColsFields('prize_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
        $dt->addColsFields('result', array('templet' => '#userdetail', 'sort' => false, 'width' => 70));
        $dt->addColsFields('money_match_time', array('templet' => '#userdetail', 'sort' => false, 'width' => 200));
        $dt->addColsFields('order_status', array('sort' => false, 'width' => 80));
        $dt->addColsFields('account_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 110));
        $dt->addColsFields('roll_ratify', array('sort' => false, 'width' => 90));
        //$arr[] = 'view';
//        if (checkRriv('/admin/CheckRolling/edit')) {
//            $arr[] = 'edit';
//        }
//        $dt->setToolBar($arr, array('width' => 70));
        $dt->enableCheckBox();
        return view('sports/sports_search', $dt->render($request));
    }

    //查询赛事结果
    // function Sairesult(Req $req){
    // $did = $req->did;
    // $qlgame = $req->qlgame?$req->qlgame:'zq';
    // $newapp = \App\Models\SportsNoteList::where('id', $did)->first();

    // if($qlgame=='zq'){
    //     if($newapp['match_id']){
    //         $newre = new \App\Models\Stzqresult();
    //         $teamname = $newre->matchjg($newapp['match_id']);
    //     }else{
    //         $teamname ='';
    //     }
    // }elseif($qlgame=='lq'){
    //     if($newapp['match_id']){
    //         $newre = new \App\Models\Stlqresult();
    //         $teamname = $newre->matchjg($newapp['match_id']);
    //     }else{
    //         $teamname ='';
    //     }
    // }elseif($qlgame=='bq'){
    //     if($newapp['match_id']){
    //         $newre = new \App\Models\Stbqresult();
    //         $teamname = $newre->matchjg($newapp['match_id']);
    //     }else{
    //         $teamname ='';
    //     }
    // }elseif($qlgame=='wq'){
    //     if($newapp['match_id']){
    //         $newre = new \App\Models\Stwqresult();
    //         $teamname = $newre->matchjg($newapp['match_id']);
    //     }else{
    //         $teamname ='';
    //     }
    // }else{
    //     $data = "参数错误";
    // }

    // $data =array(
    //     'singleresult' => json_decode($newapp['single_result'],true),
    //     'teamname' => $teamname,
    // );
    // return $data;
    // }
    // function Sairesult(Req $req){
    //     $did = $req->did;
    //     $model = \App\Models\SportsNoteList::where('id', $did)->first();
    //     $pid = $model['match_id'];
    //     $saisjg = \App\Models\Stzqresult::where('match_id',$pid)->first()->toArray();//赛事结果
    //     $saisjg['corner_ball'] = json_decode($saisjg['corner_ball'],true);
    //     $saisjg['first_score'] = json_decode($saisjg['first_score'],true);
    //     $saisjg['penalty_card'] = json_decode($saisjg['penalty_card'],true);
    //     $saisjg['warn_more'] = json_decode($saisjg['warn_more'],true);

    // }

    //结果添加
    function addend(Req $req)
    {
        $did = $req->did;//59;//
        $qlgame = $req->qlgame;//1;
        $model = \App\Models\SportsNoteList::where('id', $did)->first();
        $pid = $model['match_id'];

        if ($qlgame == 1) {
            if ($model['result_flag'] != 1) {
                $saisjg = \App\Models\Stzqresult::where('match_id', $pid)->first()->toArray();//赛事结果
                $saisjg['corner_ball'] = json_decode($saisjg['corner_ball'], true);
                $saisjg['first_score'] = json_decode($saisjg['first_score'], true);
                $saisjg['penalty_card'] = json_decode($saisjg['penalty_card'], true);
                $saisjg['warn_more'] = json_decode($saisjg['warn_more'], true);

                $model->single_result = json_encode([$saisjg], JSON_UNESCAPED_UNICODE);
                $model->save();
            }
            $newm = \App\Models\SportsNoteList::where('id', $did)->first();
            return $newm['single_result'];
        } else {
            $new = \App\Models\SportsNoteList::where('id', $did)->first();
            $newa = json_decode($new['single_result'], true);
            $newa[0]['home_score'] = $req->home_score;//主队进球
            $newa[0]['guest_score'] = $req->guest_score;//客队进球
            $newa[0]['all_goal'] = intval($req->guest_score) + intval($req->home_score);//总进球
            $newa[0]['last_score'] = $req->lastscore ? $req->lastscore : '';//最后进球球队
            $newa[0]['match_winer'] = $req->matchwiner ? $req->matchwiner : '';//赢球球队
            $newa[0]['update_time'] = time();//更新时间
            $newa[0]['u_guest_score'] = $req->u_guest_score;//上半场-主队进球数
            $newa[0]['u_home_score'] = $req->u_home_score;//上半场-客队进球数
            $newa[0]['penalty_card'] = array(
                'home' => $req->homeallcard,
                'guest' => $req->guestallcard,
                'home_half' => $req->homehalfcard,
                'guest_half' => $req->guesthalfcard,
            );
            $newa[0]['corner_ball'] = array(
                'home' => $req->homeallcorner,
                'guest' => $req->guestallcorner,
                'home_half' => $req->homehalfcorner,
                'guest_half' => $req->guesthalfcorner,
            );
            //最新进球
            $newa[0]['first_score'] = array(
                'teamscore' => $req->firstscore ? $req->firstscore : 0,//最先进球球队
                'scoretime' => $req->onescoretime ? $req->onescoretime : '',//进球时间
                'scoretype' => $req->firststye ? $req->firststye : '',//进球方式
            );

            $model->single_result = json_encode($newa, JSON_UNESCAPED_UNICODE);
            $model->result_flag = 1;

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

    function getinfo()
    {
        $page = Request::has('page') ? Request::get('page') : '';
        $list = Request::has('limit') ? Request::get('limit') : 10;
        $account = Request::get('account') ? Request::get('account') : '';
        $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' : '';
        $order_id = Request::get('order_id') ? Request::get('order_id') : '';
        $match_id = Request::get('match_id') ? Request::get('match_id') : '';
        $status = Request::has('status') ? Request::get('status') : '-1';
        $order_status = Request::has('order_status') ? Request::get('order_status') : '';
        $sureblur = Request::has('sureblurs') ? Request::get('sureblurs') : 'off';
        $type = Request::has('type') ? Request::get('type') : 'zq';
        $where = array();
        if (!empty($account)) {
            if (empty($sureblur) || $sureblur == 'off') {
                $where[] = array('money_buy_simplex.account_name', 'like', '%' . $account . '%');
            } else {
                $where[] = array('money_buy_simplex.account_name', '=', $account);
            }
        }
        if (!empty($star_time)) {
            if (!empty($end_time)) {
                $where[] = array('money_buy_simplex.money_time', '>', $star_time);
                $where[] = array('money_buy_simplex.money_time', '<', $end_time);
            } else {
                $where[] = array('money_buy_simplex.money_time', '>', $star_time);
            }
        } else if (empty($star_time)) {
            if (!empty($end_time)) {

                $where[] = array('money_buy_simplex.money_time', '<', $end_time);
            }
        }
        if (!empty($order_id)) {
            $where[] = array('money_buy_simplex.order_id', $order_id);
        }
        if (!empty($match_id)) {
            $where[] = array('money_buy_simplex.match_id', $match_id);
        }
        if ($status != -1) {
            $where[] = array('money_buy_simplex.settle_status', '=', $status);
        }
        if ($order_status != -1) {
            $where[] = array('money_buy_simplex.status', '=', $order_status);
        }
        $where[] = array('money_buy_simplex.game_code', $type);
        $newapp = new \App\Models\SportsNoteList();
        $data = $newapp->info($list, $page, $where, $type);

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

    /**
     *单式注单通过审核
     */
    public function check(Req $req)
    {
        $id = $req->id;
        if (intval($id) < 1) {
            return -1;
        }
        \App\Models\SportsNoteList::where('id', $id)->update(['roll_ratify' => '1']);
        return 1;
    }

    /**
     *单式注单拒绝审核
     */
    public function nocheck(Req $req)
    {
        $id = $req->id;
        if (intval($id) < 1) {
            return -1;
        }
        $order = \App\Models\SportsNoteList::where('id', $id)->first();
        //用戶账户金额
        $account_money = \App\Models\Account_detailed::where('account_identity', $order->account_identity)->first();
        //反水
        $water_return_money = \App\Models\Money_details::where('trade_id', $order->order_id)->where('trade_type', '7')->first();
        if (!empty($water_return_money)) {
            $water_return = $water_return_money->money;
        } else {
            $water_return = 0;
        }
        //审核不通过用户账户金额
        $available_cash = $account_money->available_cash;
        $new_available_cash = $available_cash + $order->money - $order->gain_money - $water_return;

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

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

    /**
     *单式注单作废
     */
    public function invalid(Req $req)
    {
        $id = $req->id;
        if (intval($id) < 1) {
            return -1;
        }
        $order = \App\Models\SportsNoteList::where('id', $id)->first();
        //用戶账户金额
        $account_money = \App\Models\Account_detailed::where('account_identity', $order->account_identity)->first();
        //反水
        $water_return_money = \App\Models\Money_details::where('trade_id', $order->order_id)->where('trade_type', '7')->first();
        if (!empty($water_return_money)) {
            $water_return = $water_return_money->money;
        } else {
            $water_return = 0;
        }
        //撤单后用户账户金额
        $available_cash = $account_money->available_cash;
        $new_available_cash = $available_cash + $order->money - $order->gain_money - $water_return;

        $model = new \App\Models\Money_details();
        $model->info_identity = UUID();
        $model->trade_id = $order->order_id;
        $model->account_name = $order->account_name;
        $model->account_identity = $order->account_identity;
        $model->money = abs($order->money - $order->gain_money - $water_return);
        $model->money_time = date("Y-m-d H:i:s", time());
        if ($new_available_cash > $available_cash) {
            $model->money_type = '1';
        } else {
            $model->money_type = '2';
        }
        $model->money_cash = $new_available_cash;
        $model->trade_type = '3';
        $model->trade_desc = '管理员作废单式注单';
        $model->status = '1';
        try {
            DB::beginTransaction();//开启事务
            \App\Models\SportsNoteList::where('id', $id)->update(['status' => '2'], ['gain_money' => '0']);
            \App\Models\Account_detailed::where('account_identity', $order->account_identity)->update(['available_cash' => $new_available_cash, 'cash' => $new_available_cash]);
            $model->save();

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

    /**
     *单式注单首次结算
     */
    public function settlement(Req $req)
    {
        $id = $req->id;
        if (intval($id) < 1) {
            return -1;
        }
        $order = \App\Models\SportsNoteList::where('id', $id)->first();
        $order_id = $order->order_id;
        $order_ids = array($order->order_id);
        $match_id = $order->match_id;
        $game_code = $order->game_code;
        $bet_type = 1;//单式注单
        //return $match_id;
        //判断输赢
        $settlementWinFail = new SettlementWinFail();
        $res = $settlementWinFail->ProcWinInfoByOneOrder($match_id, $order_id, $bet_type);
        //结算
        $SettlementOrder = new SettlementOrder();
        $settype = 1; //首次结算
        $data = $SettlementOrder->reSettlement($order_ids, $bet_type, $settype, $game_code, $match_id, $match_status = 0);
        return $data;
    }


    /**
     *单式注单重新结算
     */
    // public function resettlement(Req $req) {
    //     $id = $req->id;
    //     if (intval($id) < 1) {
    //         return -1;
    //     }
    //     $order = \App\Models\SportsNoteList::where('id',$id)->first();
    //     $match_id = $order->match_id;
    //     $game_code = $order->game_code;
    //     $order_id = $order->order_id;
    //     $order_ids = array($order->order_id);
    //     //return $match_id;
    //     $bet_type = 1;//单式注单
    //     //重新判断输赢
    //     $settlementWinFail = new SettlementWinFail();
    //     $res = $settlementWinFail->ProcWinInfoByOneOrder($match_id, $order_id, $bet_type);
    //     //结算
    //     $SettlementOrder = new SettlementOrder();
    //     $settype = 2; //重新结算
    //     $data = $SettlementOrder->reSettlement($order_ids,$bet_type,$settype,$game_code,$match_id,$match_status=0);
    //     return $data;
    // }
    public function resettlement(Req $req)
    {
        $order_id = $req->order_id;
        $type = $req->type;
        $match_id = $req->match_id;
        $jsurl = config('sconstant.url');//结算请求域名地址
        $token = session('adminInfo.token');
        //查询是否有订单
        $newapp = new \App\Models\SportsNoteList();
        $simplexnum = $newapp->onlyorder($order_id);
        if ($simplexnum == 1) {
            $requet = file_get_contents($jsurl . "/DoWinFailOneOrder?order_id=" . $order_id . "&token=" . $token);
            if (json_decode($requet, true)['status'] == 1) {
                $napp = new \App\Models\Stzqresult();
                $simplex = array(
                    'token' => $token,
                    'order_ids' => $order_id, //订单id字符串，用半角都好分隔
                    'bettype' => 1, //结算类型  1单式  2串式
                    'settype' => 2, //结算次数  1首次  2非首冷饮
                    'game_code' => $type, //赛事类型  zq lq wq bq
                    'match_id' => $match_id, // 赛事ID
                    'change_status' => 0   //是否改状态
                );
                $url = $jsurl . '/Settelement';
                $simplex_res = $napp->post_curls($url, $simplex);//返回json
                $huawei_res = json_decode($simplex_res, true);
                if ($huawei_res['status'] == 1) {
                    return json_encode(['status' => 1, 'msg' => '结算成功']);
                } else {
                    return json_encode(['status' => 4, 'msg' => '结算失败']);
                }
            } else {
                return json_encode(['status' => 3, 'msg' => '输赢判断错误']);
            }
        } else {
            return json_encode(['status' => 2, 'msg' => '订单不存在']);
        }
    }

    /**
     *单式注单批量结算
     */
    public function batchsettlement()
    {
        $orders = \App\Models\SportsNoteList::where('settle_status', '1')->get();
        $order_ids = array();
        for ($i = 0; $i < count($orders); $i++) {
            $result = \App\Models\MoneyBuyMatch::where('batch_id', $orders[$i]->batch_id)->where('match_id', $orders[$i]->match_id)->get();
            $res = array();
            for ($j = 0; $j < count($result); $j++) {
                $res[] = $result[$j]->result;
            }
            if (!in_array(0, $res)) {
                $order_ids[] = $orders[$i]->order_id;
            }
        }
        $SettlementOrder = new SettlementOrder();
        $bet_type = 1;//单式注单
        $data = $SettlementOrder->reSettlement($order_ids, $bet_type);
        return $data;
    }

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

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

    }

    /**
     * 投注金额统计
     */
    function moneycount()
    {
        $where = Request::has('where') ? Request::get('where') : '';
        $type = Request::has('type') ? Request::get('type') : 'zq';
        $db = new \App\Models\SportsNoteList;

        $data = $db->MoneyCount($where, $type);
        return responseToJson($data);
    }

    //单式订单数据
    public function manualmatchget(Req $req)
    {
        $order_id = isset($req->order_id) ? $req->order_id : 0;
        $model = new  \App\Models\SportsNoteList();
        $ret = $model->getorder($order_id);
        if ($ret) {
            $ret = $ret->toArray();
            return responseToJson(1, '成功', $ret);
        } else {
            return responseToJson(-1, 'false', $ret);
        }

    }

    //单式订直接手动更改输赢结果并结算
    public function manualmatchpdate(Req $req)
    {
        $order_id = isset($req->order_id) ? $req->order_id : 0;
        $datas = isset($req->matchdata) ? $req->matchdata : [];
        $datas = json_decode($datas, true);
        if (empty($order_id) || empty($datas)) {
            return responseToJson(-1, '参数不能为空！');
        }

        $model = new  \App\Models\SportsNoteList();
        $modeldata = $model->getorder($order_id);
        if (empty($modeldata)) {
            return responseToJson(-1, 'false');
        }

        $sdataArr = [];
        foreach ($datas as $val) {
            $tmp_id = $val['id'];
            $tmp_result = intval($val['result']);
            $tmp_matchword = trim($val['matchresult']);
            if (!in_array($tmp_result, [-1, 1, 2, 3, 4])) {
                continue;
            }
            $sdataArr[$tmp_id] = ['result' => $tmp_result, 'matchresult' => $tmp_matchword];
        }
        if (empty($sdataArr)) {
            return responseToJson(-2, '没有要更新的数据');
        }

        $chageNum = 0;
        foreach ($modeldata->matchdatas as $key => $val) {
            $id = $val->id;
            if (isset($sdataArr[$id])) {
                if ($val->result != $sdataArr[$id]['result'] || $val->matchwork != $sdataArr[$id]['matchresult']) {
                    $val->result = $sdataArr[$id]['result'];
                    $val->matchresult = $sdataArr[$id]['matchresult'];
                    $val->save();
                    $chageNum++;
                }
            }
        }
        if ($chageNum) {
            $modeldata->is_manual = 1;
            $modeldata->save();
        } else {
            return responseToJson(1, '没有更新操作数据!');
        }

        $data = [
            'token' => 'oclatv15689731035d84a12f550df',    //外网
            'order_ids' => $modeldata->order_id,
            'bettype' => 1,
            'settype' => 2,
            'game_code' => $modeldata->game_code,
            'match_id' => $modeldata->match_id,
            'change_status' => 0,
            'is_manual' => 1,
        ];
        $ret = $this->request_post('http://stadmin.bocai108.com:9094/Settelement', $data);

        return responseToJson(1, '更新成功');

    }


    private function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }


}