<?php


namespace App\Http\Controllers\Admin;


use App\Http\helper\Helper;
use App\Http\helper\NumConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReturnWaterController
{
    public function config(Request $request)
    {
        $date = date('Ymd');
        $kind_id = $request->post('kind_id');

        $game_level = $request->post('game_level');

        $toArr = explode('-', $game_level);
        $GameID = $toArr[0] ?? '';
        $SortID = $toArr[1] ?? '';


        $gameType = $request->gameType ?: '';

        $room_list = [];
        $kindID_arr = [1005, 2030, 2050, 2060, 2061, 2010, 2012, 3010];


        if (!empty($kind_id)) {
            $where[] = ['ki.KindID', '=', $kind_id];
            $room_list = DB::connection('write')->table('QPPlatformDB.dbo.RoomConfig')
                ->where('GameID', $GameID)
                ->select('GameID', 'RoomName', 'SortID')
                ->get();

        }

        $where = [];

        !empty($GameID) && $where[] = ['rc.GameID', $GameID];
        !empty($SortID) && $where[] = ['rc.SortID', $SortID];

        // 游戏类型搜索
        if (!empty($gameType)) {
            $gameType = explode(',', $gameType);

            $where[] = [function ($query) use ($gameType) {
                $query->whereIn('rc.GameID', $gameType);
            }];
        }

        $game_name = DB::connection('read')->table('QPPlatformDB.dbo.GameKindItem')
            ->whereIn('GameID', config('games.openKGame'))//Helper::Games)
            ->pluck('KindName as GameName', 'GameID');//单选框数据

        $KindName = DB::connection('read')->table('QPPlatformDB.dbo.GameKindItem')->pluck('KindName', 'GameID')->toArray();


        $GameRoomInfo = DB::connection('read')->table('QPPlatformDB.dbo.GameRoomInfo')->select('ServerID', 'GameID', 'SortID', 'CellScore', 'MinEnterScore')->get();

        $list = DB::connection('write')->table('QPPlatformDB.dbo.RoomConfig as rc')
            ->leftJoin('QPPlatformDB.dbo.RoomStockDay as rsd', function ($join) use ($date) {
                $join->on('rc.GameID', 'rsd.GameID')->on('rc.SortID', 'rsd.SortID')->where('DateID', $date);
            })
            ->leftjoin('QPPlatformDB.dbo.RoomStockStatic as rs', function ($join) {
                $join->on('rsd.GameID', 'rs.GameID')->on('rsd.SortID', 'rs.SortID');
            })
            ->leftJoin('QPPlatformDB.dbo.GameBetConfig as gc', function ($join) {
                $join->on('rc.GameID', 'gc.GameID')->on('rc.SortID', 'gc.SortID');
            })
            ->where($where)
            ->select('rc.GameID', 'rc.SortID', 'gc.Rate')
            ->selectRaw('IsNull(Revenue,0) Revenue,IsNull(RevenueD,0) RevenueD,IsNull(Stock,0) Stock,IsNull(TurnOver,0) TurnOver,IsNull(Winlost,0) Winlost,RoomName')
            ->orderBy('rc.GameID')
            ->paginate(10);

        foreach ($list as &$value) {

            $value->WinRate = $value->LostRate = $value->ServerID = $value->CellScore = $value->MinEnterScore = '';

            foreach ($GameRoomInfo as $val) {
                if (($value->GameID == $val->GameID) && ($value->SortID == $val->SortID)) {
                    $value->ServerID = $val->ServerID;
                    $value->CellScore = $val->CellScore / NumConfig::NUM_VALUE;
                    $value->MinEnterScore = $val->MinEnterScore / NumConfig::NUM_VALUE;
                    continue;
                }
            }

            $value->KindName = $KindName[$value->GameID] ?? '';
            $value->ShaLv = (int)$value->TurnOver > 0 ? round(($value->Winlost / $value->TurnOver) * 100, 2) : 0;
            $value->Stock /= NumConfig::NUM_VALUE;
            $value->Revenue /= NumConfig::NUM_VALUE;
            $value->RevenueD /= NumConfig::NUM_VALUE;
            $value->TurnOver /= NumConfig::NUM_VALUE;
            $value->Winlost /= NumConfig::NUM_VALUE;
            $value->Rate /= NumConfig::NUM_VALUE;


            // 当前系统输赢概率
            $ShaLv = $value->ShaLv * NumConfig::NUM_VALUE;
            $first = DB::connection('write')->table('QPPlatformDB.dbo.RoomStockConfig')
                ->where('GameID', $value->GameID)
                ->where('SortID', $value->SortID)
                ->whereRaw("$ShaLv between KillRateMin and KillRateMax")
                ->first();

            if ($first) {
                $value->WinRate = round($first->WinRate / NumConfig::NUM_VALUE, 2) . '%';
                $value->LostRate = round($first->LostRate / NumConfig::NUM_VALUE, 2) . '%';
            }
            switch ($value->SortID) {
                case 1:
                    $value->SortIDTxt = '初级场';
                    break;
                case 2:
                    $value->SortIDTxt = '普通场';
                    break;
                case 4:
                    $value->SortIDTxt = '中级场';
                    break;
                case 8:
                    $value->SortIDTxt = '高级场';
                    break;
                case 64:
                    $value->SortIDTxt = '包厢';
                    break;
                default:
                    $value->SortIDTxt = $value->SortID;
                    break;
            }
        }
        unset($value);

        $totalSwitch = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'GameBetMaxControl')->first()->StatusValue ?? '';
        if (!empty($gameType)) {
            $gameType = implode(',', $gameType);
        }
        return view('admin.return_water.config', [
            'list' => $list,
            'kind_id' => $kind_id,
            'game_level' => $game_level,
            'game_name' => $game_name,
            'room_list' => $room_list,
            'gameType' => $gameType,
            'SortID' => $SortID,
            'totalSwitch' => $totalSwitch
        ]);
    }

    // 修改房间反水比例
    public function update(Request $request, $GameID)
    {
        $SortID = $request->SortID;

        if ($request->isMethod('post')) {
            $post = $request->post();
            $post['GameID'] = $GameID;
//            $post['Rate'] /= NumConfig::NUM_VALUE;
            $post['Status'] = 1;

            DB::connection('write')->table('QPPlatformDB.dbo.GameBetConfig')
                ->updateOrInsert(['GameID' => $GameID, 'SortID' => $SortID], $post);
            return apiReturnSuc();
        } else {
            $name = DB::connection('write')->table('QPPlatformDB.dbo.RoomConfig')
                    ->where('GameID', $GameID)
                    ->where('SortID', $SortID)
                    ->first()->RoomName ?? '';
            $Rate = DB::connection('write')->table('QPPlatformDB.dbo.GameBetConfig')
                    ->where('GameID', $GameID)
                    ->where('SortID', $SortID)
                    ->first()->Rate ?? 0;
//            $Rate *= 100;
            return view('admin.return_water.update', compact('GameID', 'SortID', 'name', 'Rate'));
        }
    }

    // 渠道列表
    public function gear()
    {
        $list = DB::connection('write')->table('QPPlatformDB.dbo.GameBetMax')->get();
        foreach ($list as &$value) {
            $value->BetMax /= NumConfig::NUM_VALUE;
        }

        return view('admin.return_water.gear', [
            'list' => $list
        ]);
    }

    // 添加渠道
    public function gear_add(Request $request)
    {
        if ($request->isMethod('post')) {
            $post = $request->post();
            $ChargeMin = $post['ChargeMin'];
            $ChargeMax = $post['ChargeMax'];
            $post['BetMax'] *= NumConfig::NUM_VALUE;
            $first = DB::connection('write')->table('QPPlatformDB.dbo.GameBetMax')
                ->whereRaw("($ChargeMin between ChargeMin and ChargeMax or $ChargeMax between ChargeMin and ChargeMax)")
                ->first();
            if ($first) {
                return apiReturnFail('档位已存在');
            }

            DB::connection('write')->table('QPPlatformDB.dbo.GameBetMax')->insert($post);
            return apiReturnSuc();
        } else {
            return view('admin.return_water.gear_add');
        }
    }

    // 修改渠道
    public function gear_update(Request $request, $id)
    {
        if ($request->isMethod('post')) {
            $post = $request->post();
            $ChargeMin = $post['ChargeMin'];
            $ChargeMax = $post['ChargeMax'];
            $post['BetMax'] *= NumConfig::NUM_VALUE;
            $first = DB::connection('write')->table('QPPlatformDB.dbo.GameBetMax')
                ->where('ID', '<>', $id)
                ->whereRaw("($ChargeMin between ChargeMin and ChargeMax or $ChargeMax between ChargeMin and ChargeMax)")
                ->first();

            if ($first) {
                return apiReturnFail('档位已存在');
            }

            DB::connection('write')->table('QPPlatformDB.dbo.GameBetMax')->where('ID', $id)->update($post);
            return apiReturnSuc();
        } else {
            $info = DB::connection('write')->table('QPPlatformDB.dbo.GameBetMax')->where('ID', $id)->first();
            $info->BetMax /= NumConfig::NUM_VALUE;
            return view('admin.return_water.gear_update', [
                'info' => $info
            ]);
        }
    }

    // 修改状态
    public function gear_status(Request $request, $id)
    {
        $status = $request->status ?: 1;

        DB::connection('write')->table('QPPlatformDB.dbo.GameBetMax')->where('ID', $id)->update(['Status' => $status]);
        return apiReturnSuc();
    }

    public function totalSwitch(Request $request)
    {
        $status = $request->status ?: 1;

        DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'GameBetMaxControl')
            ->update(['StatusValue' => $status]);
        return apiReturnSuc();
    }

}
