<?php


namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Constants\Util;
use App\Http\Controllers\Controller;
use App\Models\Config;
use App\Models\RoomUser;
use App\Services\RoomService;
use App\Services\SettlementService;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Exception;
use Telegram\Bot\Api;

class Room extends Controller
{
    /**
     * @api {post} /admin/room/completed 结算
     * @apiGroup 房间管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     * @apiParam {string} room_id 房间号
     */
    public function completed()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'room_id' => ['required', 'string', 'min:1'],
            ]);
            $roomId = request()->input('room_id');
            $list = RoomUser::where('status', 3)
                ->where('room_id', $roomId)
                ->orderBy('score', 'desc')->get();
            $count = RoomUser::where('room_id', $roomId)->count();
            if ($count > 0 && count($list) == $count) {
                $totalAmount = RoomUser::where('status', 3)
                    ->where('room_id', $roomId)->sum('score');
                if ($totalAmount == 0) {
                    $list = $list->toArray();
                    $item = $list[0];
                    $res = (new SettlementService())->submitSettle($item['member_id'], $item['score']);
                    if ($res['status']) {
                        $telegram = new Api(config('services.telegram.token'));
                        foreach ($res['data'] as $r) $telegram->sendMessage($r);
                    } else {
                        throw new Exception("结算失败", HttpStatus::CUSTOM_ERROR);
                    }
                } else {
                    throw new Exception("经过系统结算，盈利额与亏损额度无法匹配，无法进行结算", HttpStatus::CUSTOM_ERROR);
                }
            } else {
                throw new Exception("用户还没有全部提交得分", HttpStatus::CUSTOM_ERROR);
            }
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(intval($e->getCode()), $e->getMessage());
        }
        return $this->success();
    }

    /**
     * @api {post} /admin/room/setScore 设置用户的得分
     * @apiGroup 房间管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     * @apiParam {int} id 房间详情ID
     * @apiParam {int} score 游戏得分
     */
    public function setScore()
    {
        DB::beginTransaction();
        try {
            request()->validate([
                'id' => ['required', 'integer', 'min:1'],
                'score' => ['required', 'integer']
            ]);
            $id = request()->input('id');
            $score = intval(request()->input('score'));
            $ru = RoomUser::where('id', $id)
                ->whereIn('status', [2,3])
                ->first();
            if (!$ru) throw new Exception('结算数据不存在', HttpStatus::CUSTOM_ERROR);
            $ru->score = $score;
            if($ru->status == 2) {
                $ru->status = 3; // 设置为待结算状态
            }
            $ru->save();
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error(intval($e->getCode()), $e->getMessage());
        }
        return $this->success();
    }

    /**
     * @api {get} /admin/room/details 对局详情
     * @apiGroup 房间管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     * @apiParam {string} room_id 房间号
     *
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.id 详情ID
     * @apiSuccess (data) {string} data.room_id 房间号
     * @apiSuccess (data) {string} data.member_id 会员ID
     * @apiSuccess (data) {string} data.game_id 游戏ID
     * @apiSuccess (data) {int} data.status 人员状态
     * - 0 待准备
     * - 1 已准备
     * - 2 游戏中
     * - 3 待结算
     * - 4 已结算
     * @apiSuccess (data) {int} data.score 得分
     * @apiSuccess (data) {float} data.brokerage 抽佣金额
     * @apiSuccess (data) {float} data.real_score 真实获得的金额
     * @apiSuccess (data) {string} data.screenshot 结算截图
     * @apiSuccess (data) {string} data.first_name 用户昵称
     */
    public function details()
    {
        try {
            request()->validate([
                'room_id' => ['required', 'string', 'min:1']
            ]);
            $roomId = request()->input('room_id');
            $res = RoomUser::where('room_id', $roomId)
                ->with('room')->get();
            foreach ($res as $item) {
                $item['screenshot'] = Util::ensureUrl($item['screenshot']);
            }


        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()), $e->getMessage());
        }
        return $this->success($res);


    }

    /**
     * @api {get} /admin/room 游戏房间
     * @apiGroup 房间管理
     *
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     *
     * @apiParam {int} [page=1]
     * @apiParam {int} [limit=10]
     * @apiParam {string} [room_id] 房间号
     * @apiParam {string} [member_id] 房主 tg会员ID
     * @apiParam {int} [status] 状态
     * - 0 创建中
     * - 1 创建完成
     * - 2 游戏中
     * - 3 已结算
     * @apiSuccess (data) {Object} data
     * @apiSuccess (data) {int} data.total 数量
     * @apiSuccess (data) {Object[]} data.data 列表
     * @apiSuccess (data) {int} data.data.id
     * @apiSuccess (data) {string} data.data.room_id 房间号
     * @apiSuccess (data) {int} data.data.member_id 房主 tg会员id
     * @apiSuccess (data) {string} data.data.game_name 游戏名称
     * @apiSuccess (data) {string} data.data.base_score 底分
     * @apiSuccess (data) {string} data.data.participants 人数
     * @apiSuccess (data) {string} data.data.rounds 局数
     * @apiSuccess (data) {string} data.data.join_count 已加入人数
     * @apiSuccess (data) {string} data.data.updated_at
     * @apiSuccess (data) {string} data.data.created_at
     * @apiSuccess (data) {int} data.data.status 状态
     * - 0 创建中
     * - 1 创建完成
     * - 2 游戏中
     * - 3 已结算
     */
    public function index()
    {
        try {
            request()->validate([
                'room_id' => ['nullable', 'string', 'min:1'],
                'member_id' => ['nullable', 'string', 'min:1'],
                'status' => ['nullable', 'integer', 'min:0', 'max:3']
            ]);
            $search = request()->all();
            $search['not_status'] = 0;
            $search['like_room_id'] = true; // 模糊查询房间号
            $result = RoomService::paginate($search);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error(intval($e->getCode()), $e->getMessage());
        }
        return $this->success($result);
    }
}