<?php


namespace App\Http\logic\admin;


use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\Http\logic\api\BaseApiLogic;
use Illuminate\Support\Facades\DB;

class GoldLogic extends BaseApiLogic
{
    // 同步库存
    public function sync_stock($serverID)
    {

        $admin = session('admin');
        $account = $admin->account ?: '';
        $password = $admin->password ?: '';

        if (empty($serverID)) {
            $this->error = '缺少参数游戏ID';
            return false;
        }

        $url = config('transfer.stock')['url'] . 'getStock';

        $data = [
            'accounts' => $account,
            'passworld' => $password,
            'serverID' => $serverID
        ];

        $build_query = $url . '?' . http_build_query($data);

        $json_decode = (new HttpCurl())->curl_get($build_query);

        $output = !empty($json_decode) ? \GuzzleHttp\json_decode($json_decode, true) : '';

        if (is_array($output)) {
            if ($output['code'] != 200) {
                $this->error = $output['msg'];
                return false;
            }

            if ($serverID != $output['data']['server_id']) {
                $this->error = '游戏ID错误';
                return false;
            }

            $output['data']['stock'] = number_float($output['data']['stock'] / NumConfig::NUM_VALUE);
            $output['data']['revenue'] = number_float($output['data']['revenue'] / NumConfig::NUM_VALUE);
            $data = $output['data'];
            return apiReturnSuc($data);

        } else {
            $this->error = '更新库存失败';
            return false;
        }

    }

    // 更新库存
    public function update_stock($serverID,$score)
    {
        $admin = session('admin');
        $account = $admin->account ?: '';
        $password = $admin->password ?: '';

        if (empty($serverID)) {
            $this->error = '缺少参数游戏ID';
            return false;
        }

        $url = config('transfer.stock')['url'] . 'addStock';

        $data = [
            'accounts' => $account,
            'passworld' => $password,
            'serverid' => $serverID,
            'score' => $score
        ];

        $build_query = $url . '?' . http_build_query($data);

        $json_decode = (new HttpCurl())->curl_get($build_query);

        if (empty($json_decode)) {
            $this->error = '服务端更新库存失败！';
            return false;
        }

        $output = \GuzzleHttp\json_decode($json_decode, true);

        if (is_array($output)) {
            if ($output['code'] != 200) {
                $this->error = $output['msg'];
                return false;
            }

            if ($serverID != $output['data']['server_id']) {
                $this->error = '游戏ID错误';
                return false;
            }

            $data = $output['data'];
            return $data;

        } else {
            $this->error = '更新库存失败';
            return false;
        }
    }


    /**
     * 游戏控制
     * @param array $where // 搜索条件
     * @param array $ServerIDs // 试玩场搜索条件
     * @param bool $demo true=>试玩场  false => 正式场
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Pagination\LengthAwarePaginator\
     */
    public function gameConfigList($where, $ServerIDs, $demo = false)
    {

        $filed = ['gi.GameID', 'gi.ServerID as gi_ServerID', 'gri.Nullity','gi.ServerName', 'gi.RoomStock', 'ki.KindName', 'ki.KindID', 'si.*'];

        // 试玩场
        $sql = DB::connection('read')->table('QPPlatformDB.dbo.GameRoomInfo as gi')
            ->join('QPPlatformDB.dbo.GameRoomInfo as gri', function ($join){
                $join->on('gi.ServerID', 'gri.ServerID');
            });



        $list = $sql
            ->leftJoin('QPPlatformDB.dbo.GameKindItem as ki', 'ki.GameID', '=', 'gi.GameID')
            ->leftJoin('QPTreasureDB.dbo.StockConfigInfo as si', 'gi.ServerID', 'si.ServerID')
            ->select($filed)
            ->where($where)
            ->whereIn('gi.GameID',$ServerIDs)
            ->orderBy('gi.GameID', 'asc')
            ->orderBy('gi.ServerName', 'asc')
            ->paginate(10);

        $allRevenue = DB::connection('read')->table('QPRecordDB.dbo.RecordGameInfo')->selectRaw('ServerID,sum(Revenue) as Revenue')->groupBy('ServerID')->pluck('Revenue', 'ServerID')->toArray();

        foreach ($list as &$val) {

            $ServerID = $val->gi_ServerID;

            // 房间累计税收
            $Revenue = 0;
            if (array_key_exists($ServerID, $allRevenue)) {
                $Revenue = $allRevenue[$ServerID];
            }
            $val->Revenue = number_float($Revenue / 100);


            // 当前触发概率
            $to_arr = explode(';', rtrim($val->RoomStock, ';'));

            // 暗税
            $darkRevenue = (isset($to_arr[0]) && !empty($to_arr[0]) && $val->GameID == 1005) ? explode(':', $to_arr[1])[1] : 0;

            if (isset($to_arr[0]) && !empty($to_arr[0])) {
                $stock = explode(':', $to_arr[0])[1];
            } else {
                $stock = 0;
            }


            $val->RoomStock = number_float($stock / 100);
            $val->darkRevenue = number_float($darkRevenue / 100);

            /*
             * 库存 / 档位
             * 大于0 倍数 * 输基础概率值 + 输的初始概率值  比较最大输的值  取最小
             * 等于 0
             * 小于0 倍数 * 赢基础概率值 + 赢的初始概率值  比较最大赢的值  取最小
             * */
            // 取反
            if ($stock < 0) {
                $stock1 = -$stock;
            } else {
                $stock1 = $stock;
            }

            if ($val->BaseScore && $stock1 > $val->BaseScore) {
                $res = floor($stock / $val->BaseScore);

                switch ($res) {
                    case $res > 0:
                        $lost = $res * $val->LostBasePercent + $val->LostInitPercent;
                        if ($lost > $val->LostMaxPercent) {
                            $val->gailv = $val->LostMaxPercent;
                        } else {
                            $val->gailv = $lost;
                        }
                        break;
                    case $res == 0:
                        $val->gailv = 0;
                        break;
                    case $res < 0:
                        $win = -$res * $val->WinBasePercent + $val->WinInitPercent;

                        if ($win > $val->WinMaxPercent) {
                            $val->gailv = $val->WinMaxPercent;
                        } else {
                            $val->gailv = $win;
                        }
                }
                $val->gailv = number_float($val->gailv);
            } else {
                $val->gailv = '';
            }

            $val->BaseScore = $val->BaseScore > 0 ? number_float($val->BaseScore / 100) : '';


        }
        return $list;
    }
}
