<?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\MoneyBuyStr as MoneyBuyStrModel;
use App\Models;
use Request;

/**1
 *
 */
class SoccerStringNoteListController 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['status'] = isset($req->status) ? trim($req->status) : '-1';
        $request['match_id'] = isset($req->match_id) ? trim($req->match_id) : '';
        $request['game_code'] = isset($req->game_code) ? trim($req->game_code) : '';
        $request['order_status'] = isset($req->order_status) ? trim($req->order_status) : '-1';

        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/SoccerStringNoteList/info');
        $dt->setLang('sportsnotelist');
        //$dt->addColsFields('id', array('templet' => '#userdetail', 'sort' => true, 'width' => 80));
        $dt->addColsFields('order_id', array('templet' => '#userdetail', 'sort' => true, 'width' => 210, 'minWidth' => 200));
        $dt->addColsFields('str_type', array('templet' => '#userdetail', 'sort' => false, 'width' => 120));
        $dt->addColsFields('detail_content', array('sort' => false, 'width' => 150));
        $dt->addColsFields('money', array('templet' => '#userdetail', 'sort' => false, 'width' => 90));
        $dt->addColsFields('water_return', array('templet' => '#userdetail', 'sort' => false, 'width' => 90));
        $dt->addColsFields('prize_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 120));
        $dt->addColsFields('result', array('templet' => '#moneywater', 'sort' => false, 'width' => 90));
        $dt->addColsFields('money_time', array('templet' => '#userdetail', 'sort' => false, 'width' => 140));
        $dt->addColsFields('order_status', array('sort' => false, 'width' => 80));
        $dt->addColsFields('account_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 230));
        //$dt->addColsFields('myoption', array('templet' => '#myoption', 'sort' => false, 'title' => '操作', 'width' => 120));
        //$dt->addColsFields('settle_status', array('sort' => false, 'width' => 90));
        //if (checkRriv('/admin/SoccerStringNoteList/edit')) {
        //    $arr[] ='edit';
        // }
        //$dt->setToolBar($arr, array('width' => 100));
        //$dt->enableCheckBox();
        return view('sports/sports_stringnotelist', $dt->render($request));
    }


    public function notelistSet(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['status'] = isset($req->status) ? trim($req->status) : '-1';
        $request['match_id'] = isset($req->match_id) ? trim($req->match_id) : '';
        $request['game_code'] = isset($req->game_code) ? trim($req->game_code) : '';
        $request['order_status'] = isset($req->order_status) ? trim($req->order_status) : '-1';

        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/SoccerStringNoteList/info');
        $dt->setLang('sportsnotelist');
        //$dt->addColsFields('id', array('templet' => '#userdetail', 'sort' => true, 'width' => 80));
        $dt->addColsFields('order_id', array('templet' => '#userdetail', 'sort' => true, 'width' => 210, 'minWidth' => 200));
        $dt->addColsFields('str_type', array('templet' => '#userdetail', 'sort' => false, 'width' => 120));
        $dt->addColsFields('detail_content', array('sort' => false, 'width' => 150));
        $dt->addColsFields('money', array('templet' => '#userdetail', 'sort' => false, 'width' => 90));
        $dt->addColsFields('water_return', array('templet' => '#userdetail', 'sort' => false, 'width' => 90));
        $dt->addColsFields('prize_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 120));
        $dt->addColsFields('result', array('templet' => '#moneywater', 'sort' => false, 'width' => 90));
        $dt->addColsFields('money_time', array('templet' => '#userdetail', 'sort' => false, 'width' => 140));
        $dt->addColsFields('order_status', array('sort' => false, 'width' => 80));
        $dt->addColsFields('account_money', array('templet' => '#userdetail', 'sort' => false, 'width' => 230));
        $dt->addColsFields('myoption', array('templet' => '#myoption', 'sort' => false, 'title' => '操作', 'width' => 120));
        //$dt->addColsFields('settle_status', array('sort' => false, 'width' => 90));
        //if (checkRriv('/admin/SoccerStringNoteList/edit')) {
        //    $arr[] ='edit';
        // }
        //$dt->setToolBar($arr, array('width' => 100));
        //$dt->enableCheckBox();
        return view('sports/sports_stringnotelistSet', $dt->render($request));
    }


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

        $where = array();
        if (!empty($account)) {
            if (empty($sureblur) || $sureblur == 'off') {
                $where[] = array('money_buy_str.account_name', 'like', '%' . $account . '%');
            } else {
                $where[] = array('money_buy_str.account_name', '=', $account);
            }
        }
        if (!empty($star_time)) {
            if (!empty($end_time)) {
                $where[] = array('money_buy_str.money_time', '>', $star_time);
                $where[] = array('money_buy_str.money_time', '<', $end_time);
            } else {
                $where[] = array('money_buy_str.money_time', '>', $star_time);
            }
        } else if (empty($star_time)) {
            if (!empty($end_time)) {

                $where[] = array('money_buy_str.money_time', '<', $end_time);
            }
        }
        if (!empty($order_id)) {
            $where[] = array('money_buy_str.order_id', $order_id);
        }

        $ids = array();
        if (!empty($match_id)) {
            $allcs = new \App\Models\MoneyBuyMatch();
            $csorder = $allcs->allstrorder($match_id, $game_code);
            if (!empty($csorder)) {
                for ($i = 0; $i < count($csorder); $i++) {
                    $ids[] = $csorder[$i]['order_id'];
                }
            } else {
                return \App\Lib\DataTable\DataTable::init()->toJson([]);
            }
        }

        //调整状态查询 1,2,3为订单状态 1投注 2作废 3撤单
        if ($order_status == 1 || $order_status == 2 || $order_status == 3) {
            $where[] = array('money_buy_str.status', '=', $order_status);
        }
        //4 5为结算状态 4未结算 5已结算
        if ($order_status == 4) {
            $status = 1;
            $where[] = array('money_buy_str.settle_status', '=', $status);
        }
        if ($order_status == 5) {
            $status = 2;
            $where[] = array('money_buy_str.settle_status', '=', $status);
        }


        /*
            
        if ($status != -1) {
            $where[] = array('money_buy_str.settle_status', '=', $status);
        }
        if ($order_status != -1) {
            $where[] = array('money_buy_str.status', '=', $order_status);
        }
        */
        $newapp = new \App\Models\MoneyBuyStr();
        $data = $newapp->getinfo($list, $page, $where, $ids);


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

    /**
     *串关注单详情
     */
    function detail(Req $req)
    {
        $id = $req->id;
        $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['match_id'] = isset($req->match_id) ? trim($req->match_id) : null;
        $dt = \App\Lib\DataTable\DataTable::init();
        $dt->setDataSource('/admin/SoccerStringNoteList/detailinfo?id=' . $id . '');
        $dt->setLang('sportsnotelist');
        $dt->addColsFields('match_id', array('templet' => '#userdetail', 'sort' => true, 'width' => 80));
        $dt->addColsFields('league', array('templet' => '#userdetail', 'sort' => false, 'width' => 120));
        $dt->addColsFields('home_guest', array('templet' => '#userdetail', 'sort' => false, 'width' => 260));
        $dt->addColsFields('content', array('templet' => '#userdetail', 'sort' => false, 'width' => 220));
        $dt->addColsFields('game_type', array('templet' => '#userdetail', 'sort' => false, 'width' => 90));
        $dt->addColsFields('time', array('templet' => '#userdetail', 'sort' => false, 'width' => 180));
        $dt->addColsFields('status', array('templet' => '#userdetail', 'sort' => false, 'width' => 80));
        $dt->addColsFields('result', array('templet' => '#userdetail', 'sort' => false, 'width' => 120));
        //$dt->enableCheckBox();
        return view('sports/sports_notelistdetail', $dt->render($request));
    }

    function detailinfo(Req $req)
    {
        $id = $req->id;

        $newapp = new \App\Models\MoneyBuyStr();
        $data = $newapp->getdetailinfo($id);

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

    /**
     *串关注单作废
     */
    public function invalid(Req $req)
    {
        $id = $req->id;
        $reason = $_GET['reason'];
        //return $reason;
        if (intval($id) < 1) {
            return -1;
        }
        //return 1;
        $order = \App\Models\MoneyBuyStr::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\MoneyBuyStr::where('id', $id)->update(['status' => '2', 'gain_money' => '0', 'use_mark' => $reason]);
            \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 resetStrOrder(Req $req)
    {
        $id = $req->id;
        if (intval($id) < 1) {
            return ['status' => -1, 'msg' => '无效id'];
        }
        $order = (new MoneyBuyStrModel())->with('matchdatas')->where('id', $id)->first();
        $game_code = $order->matchdatas['0']->game_code;
        $match_id = $order->matchdatas['0']->match_id;

        if (empty($order)) {
            return ['status' => -2, 'msg' => '订单不存在'];
        }
        if ($order->status == 1) {
            return ['status' => -3, 'msg' => '状态错误'];
        }

        $order_id = $order->order_id;
        $data = [
            'token' => session('adminInfo.token'),    //外网
            'order_id' => $order_id,
            'game_code' => $game_code,
            'match_id' => $match_id,
        ];
        $ret = request_post(config('sconstant.url') . '/ResStringOneOrder', $data);
        return json_decode($ret, true);

    }


    /**
     *串关注单首次结算
     */
    public function settlement(Req $req)
    {
        $id = $req->id;
        if (intval($id) < 1) {
            return -1;
        }
        $order = \App\Models\MoneyBuyStr::where('id', $id)->first();
        $match = \App\Models\MoneyBuyMatch::where('order_id', $order->order_id)->where('bet_type', '2')->get();
        $bet_type = 2; //串关注单
        $order_id = $order->order_id;
        for ($i = 0; $i < count($match); $i++) {
            $match_id = $match[$i]->match_id;
            $game_code = $match[$i]->game_code;
            //判断输赢
            //$match_ids[] = $match[$i]->match_id;
            $settlementWinFail = new SettlementWinFail();
            $res = $settlementWinFail->ProcWinInfoByOneOrder($match_id, $order_id, $bet_type);
        }
        $order_ids = array($order->order_id);
        //return $match_ids;
        //结算
        $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\MoneyBuyStr::where('id', $id)->first();
        $match = \App\Models\MoneyBuyMatch::where('order_id', $order->order_id)->where('bet_type', '2')->get();
        $order_id = $order->order_id;
        for ($i = 0; $i < count($match); $i++) {
            $match_id = $match[$i]->match_id;
            $game_code = $match[$i]->game_code;
            break;
        }
        //重新结算
        $data = $this->do_settelement($order_id, $game_code, $match_id);
        return $data;
    }

    //单订单手动提交结算
    private function do_settelement($order_id, $game_code, $match_id)
    {
        $data = [
            'token' => session('adminInfo.token'),    //外网
            'order_id' => $order_id,
            'bet_type' => 2,
        ];
        $ret = request_post(config('sconstant.url') . '/WinfailoneNomal', $data);
        $retarr = json_decode($ret, true);
        if (empty($ret) || empty($retarr) || !isset($retarr['status']) || $retarr['status'] != 1) {
            return ['status' => 0, 'msg' => '计算输赢失败', 'data' => ''];
        }

        $data = [
            'token' => session('adminInfo.token'),    //外网
            'order_ids' => $order_id,
            'bettype' => 2,
            'settype' => 2,
            'game_code' => $game_code,
            'match_id' => $match_id,
            'change_status' => 0,
            'is_manual' => 0,
        ];
        $ret = request_post(config('sconstant.url') . '/Settelement', $data);
        return json_decode($ret, true);
    }


    /**
     *串关注单批量结算
     */
    public function batchsettlement()
    {
        $bet_type = 2; //串关注单
        $orders = \App\Models\MoneyBuyStr::where('settle_status', '1')->get();
        $order_ids = array();
        for ($i = 0; $i < count($orders); $i++) {
            $result = \App\Models\MoneyBuyMatch::where('order_id', $orders[$i]->order_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;
            }
        }
        //return $order_id;
        $SettlementOrder = new SettlementOrder();
        $data = $SettlementOrder->reSettlement($order_ids, $bet_type);
        return $data;
    }

    //撤销某个串个订单,参数单号
    public function RevokeStrOrder(Req $req)
    {
        $order_id = $req->input('order_id');
        $model = (new MoneyBuyStrModel())->with('matchdatas')->where('order_id', $order_id)->first();
        $match_first = $model->matchdatas['0'];

        if (empty($order_id) || empty($model) || empty($match_first)) {
            return responseToJson(-2001);
        }

        $game_code = $match_first->game_code;
        $match_id = $match_first->match_id;

        $data = [
            'token' => session('adminInfo.token'),
            'order_id' => $order_id,
            'game_code' => $game_code,
            'match_id' => $match_id,
        ];

        $ret = request_post(config('sconstant.url') . '/UnsetOneStringOrder', $data);
        return json_decode($ret, true);

    }


    /**
     *删除串关注单
     */
    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\MoneyBuyStr::whereIn('id', $ids)->delete();
        if (!$rows) {
            return responseToJson(-2003); //id����
        }
        return responseToJson(1, trans('menu.delete_success')); //id����

    }

    /**
     * 投注金额统计 1
     */
    function moneycount()
    {
        $where = Request::has('where') ? Request::get('where') : '';
        $match_id = Request::has('match_id') ? Request::get('match_id') : '';
        $game_code = Request::has('game_code') ? Request::get('game_code') : '';

        $db = new \App\Models\MoneyBuyStr();

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

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