<?php

namespace App\Http\Controllers\V1;

use App\Http\Requests\StoreFictitious;
use App\Http\Requests\StoreGame;
use App\Models\CourseHole;
use App\Models\Game as GameModel;
use App\Models\Game;
use App\Models\GameFictitiou;
use App\Models\GameLooker;
use App\Models\GameType;
use App\Models\GameUser;
use App\Http\Requests\GameUser as GameUserRequest;
use App\Services\Api\UserService;
use App\Services\JPushService;
use App\Models\User;
use App\Models\UserJoin;
use App\Services\Api\GameService;
use App\Services\Api\NoticeService;
use App\Services\SortService;
use App\Services\TencentImGroupService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Util\Exception;

class GameController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->GameService = new GameService();
        $this->user = auth('api')->user();
        if (!empty($this->user->deleted_at)) {
            JPushService::updateAlias($this->user->jpush_reg_id, '');
            $this->user->online = 0;
            $this->user->save();
            auth('api')->logout();
        }
    }

    //创建比赛
    public function store(StoreGame $request, GameModel $game)
    {
        try {
            $this->GameService->store($request, $game);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }

    //比赛信息
    public function info(Request $request)
    {
        try {
            if (!$request->id) {
                throw new Exception(trans('api.PARAMS_ERROR'));
            }
            $info = GameModel::query()
                ->leftJoin('courses', 'courses.id', '=', 'games.course_id')
                ->where('games.id', $request->id)
                ->select('games.*', 'courses.name as course_name', 'courses.img as course_avatar')
                ->whereNull('games.deleted_at')
                ->first();

            if (!$info) {
                return $this->success([]);
            }
            $info['begin_time'] = date('Y-m-d H:i', strtotime($info['begin_time']));
            $info['is_had_join'] = $this->GameService->isHadJoin($info['id'], $this->user->id);
            $info['is_had_look'] = $this->GameService->isHadLook($info['id'], $this->user->id);
            $info['is_had_apply_join'] = $this->GameService->isHadApplyJoin($info['id'], $this->user->id);
            $info['is_had_invite_join'] = $this->GameService->isHadInviteJoin($info['id'], $this->user->id);
            $info['game_status'] = $this->GameService->getGameStatus($info);

            if ($info['end_time']) {
                $info['end_time'] = date('Y-m-d H:i', strtotime($info['end_time']));
            }

            $info['game_users'] = $this->GameService->getGameUsers($info['id']);

            return $this->success($info);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    //修改比赛
    public function update(StoreGame $request, GameModel $game)
    {
        try {
            if (!$this->GameService->hasAuth($this->user->id, $request->id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            if (!$request->id) {
                throw new Exception(trans('api.PARAMS_ERROR'));
            }
            if (!$this->GameService->store($request, $game)) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //修改比赛场地
    public function changeCourse(Request $request)
    {
        try {
            if (!$this->GameService->hasAuth($this->user->id, $request->game_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            if (!$request->game_id || !$request->course_id) {
                throw new Exception(trans('api.PARAMS_ERROR'));
            }
            if (!$this->GameService->saveGameCourse($request->game_id, $request->course_id)) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //检查是否有用户参加其他比赛
    public function checkGame(Request $request)
    {
        try {
            $gameId = $request->input('game_id');

            if (!$this->GameService->hasAuth($this->user->id, $gameId)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $result = $this->GameService->isUserGoingGame($gameId);

            return $this->success($result);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    //启动比赛
    public function begin(Request $request)
    {
        try {
            $gameId = $request->input('game_id');

            if (!$this->GameService->hasAuth($this->user->id, $gameId)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            if (!$this->GameService->beginGame($gameId)) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            };
            return $this->success();

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    //取消比赛
    public function cancel(Request $request)
    {
        DB::beginTransaction();
        try {
            $game = Game::query()->find($request->game_id);
            if (!$game) {
                throw new Exception(trans('api.GAME_NOT_EXIST'));
            }
            if (!$this->GameService->hasAuth($this->user->id, $request->game_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $game = Game::find($request->game_id);
            if (!$res = $game->delete()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            try {
                //解散群聊
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $data['GroupId'] = $game->GroupId;
                $groupService->destroyGroup($data);

            } catch (GuzzleException $exception) {
                Log::error('cancel：' . $exception->getMessage());
                return $this->error(trans('api.NETWORK_ERROR'));
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //比赛规模
    public function gameTypes()
    {
        $list = GameType::all()->toArray();

        return $this->success($list);
    }

    //今日赛事
    public function todayGames(Request $request)
    {
        $type = $request->input('type');
        $list = $this->GameService->getTodayGames($type);

        return $this->success($list);
    }

    //我的活动（待进行）
    public function myGames()
    {
        $list = $this->GameService->getMyGames();

        return $this->success($list);
    }

    //正在进行
    public function underway()
    {
        $info = $this->GameService->getUnderwayGame();

        return $this->success($info);
    }

    //历史球员
    public function historyPlayers()
    {
        $ids = $this->GameService->getHistoryPlayerIds();

        $list = User::query()->whereIn('id', $ids)->select('id', 'name', 'avatar', 'is_auth')->get();
        if($list->isEmpty()){
            return [];
        }
        $list = $list->toArray();
        foreach ($list as $key => &$val) {
            $val['have_user_course'] = UserService::haveUserCourse($val['id']);
        }

        return $this->success($list);
    }

    //搜索球友
    public function searchPlayers(Request $request)
    {
        $keyword = $request->keyword;
        try {
            if (empty($keyword)) {
                throw new Exception(trans('api.PARAMS_ERROR'));
            }
            $list = $this->GameService->getPlayers($keyword);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success($list);
    }

    //拉入比赛 type=1 正常球手
    public function pullGame(Request $request, GameUser $gameUserModel)
    {
        DB::beginTransaction();
        try {
            $gameId = $request->input('game_id', 0);
            $gameUsers = $request->input('game_users');

            $game = Game::query()->whereNull('deleted_at')->find($gameId);

            if (!$game) {
                throw new Exception(trans('api.GAME_NOT_EXIST'));
            }
            if (!$this->GameService->hasAuth($this->user->id, $gameId)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            if (!$this->GameService->isCanAddPlayer($gameId)) {
                throw new Exception(trans('api.MEMBER_HAD_FULL'));
            }
            if (!empty($gameUsers)) {
                $data = [];
                $userIds = [];
                $gameUsers = is_array($gameUsers) ? $gameUsers : json_decode($gameUsers, true);
                foreach ($gameUsers as $key => $val) {
                    if ($val['type'] == 2) { //虚拟球手
                        $gameFictitiou = GameFictitiou::find($val['user_id']);
                        $gameFictitiou->game_id = $gameId;
                        $gameFictitiou->save();
                        $row = [
                            'game_id' => $gameId,
                            'user_id' => $val['user_id'],
                            'type' => 2,
                            'level' => $val['level'],
                            'created_at' => Carbon::now()->toDateTimeString(),
                            'updated_at' => Carbon::now()->toDateTimeString(),
                        ];
                        array_push($data, $row); //追加到数据
                    } else {
                        $isExist = $gameUserModel::query()
                            ->where(['game_id' => $gameId, 'user_id' => $val['user_id']])
                            ->where('type', 1)
                            ->whereNull('deleted_at')
                            ->first();
                        if (!$isExist) { //尚未加入这场比赛
                            $row = [
                                'game_id' => $gameId,
                                'user_id' => $val['user_id'],
                                'type' => 1,
                                'level' => $val['level'],
                                'created_at' => Carbon::now()->toDateTimeString(),
                                'updated_at' => Carbon::now()->toDateTimeString(),
                            ];
                            array_push($data, $row); //追加到数据
                            $userIds[] = $val['user_id']; //记录新增的用户，要加入群聊用到
                        }
                        $looker = GameLooker::query()
                            ->where(['game_id' => $gameId, 'user_id' => $val['user_id']])
                            ->whereNull('deleted_at')
                            ->first();
                        if ($looker) { //如果是拉入的围观者 移除
                            $looker->delete();
                            $this->GameService->decLookersCount($gameId); //围观数 -1
                        }
                    }
                }
                $gameUserModel->addAll($data); //批量新增
                $this->GameService->incMembersCount($gameId, count($data)); //成员数增加
            }
            if (!empty($userIds)) {
                try {
                    //用户加入群聊
                    $groupService = TencentImGroupService::getInstance();
                    $groupData = [];
                    $chatUsers = User::query()->whereIn('id', $userIds)->select('id', 'name', 'avatar', 'tencent_im_user_id')->get()->toArray();
                    $groupData['member_list'] = $chatUsers;
                    $groupData['GroupId'] = $game->GroupId;
                    $groupService->addGroupMember($groupData);

                } catch (\Exception $exception) {
                    Log::error('pullGame：' . $exception->getMessage());
                    return $this->error(trans('api.NETWORK_ERROR'));
                }
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::info($exception->getLine());
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //邀请加入比赛
    public function inviteByGameCode(Request $request)
    {
        DB::beginTransaction();
        try {
            $userId = $request->user_id; //被邀请人
            $gameId = $request->game_id; //要加入的比赛
            $reason = $request->input('reason', '');

            if ($this->user->id == $userId) {
                throw new Exception(trans('api.ILLEGAL_OPERATION'));
            }
            if ($this->GameService->isHadJoin($gameId, $userId)) {
                throw new Exception(trans('api.USER_HAD_JOIN'));
            }
            $userJoin = new UserJoin();
            $userJoin->user_id = $userId;
            $userJoin->invitor_id = $this->user->id;//邀请人
            $userJoin->matter_id = $gameId;
            $userJoin->type = 2; //1球队, 2比赛
            $userJoin->status = 0; //待确认
            $userJoin->reason = $reason;
            if (!$userJoin->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            //给用户添加消息记录
            $notice = new NoticeService();
            $notice->send_msg($userId, $userJoin->id, 7, $this->user->id, 'api.INVITE_JOIN_GAME', $gameId);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }

    //加入或拒绝操作（受邀）看到按钮 "同意" 和 "拒绝"
    public function joinOrRefuse(Request $request)
    {
        DB::beginTransaction();
        try {
            $gameId = $request->game_id;
            $status = $request->input('status', 2);  //1加入，2拒绝

            if (!$game = Game::query()->find($gameId)) {
                throw new Exception(trans('api.GAME_NOT_EXIST'));
            }
            if ($status == 1) {
                $this->GameService->agreeJon($gameId, $this->user->id);
                $this->GameService->incMembersCount($gameId); //成员数+1
                try {
                    $groupService = TencentImGroupService::getInstance();
                    $data = array();
                    $data['member_list'] [] = $this->user;
                    $data['GroupId'] = $game->GroupId;
                    $groupService->addGroupMember($data);
                } catch (GuzzleException $exception) {
                    Log::error('joinOrRefuse：' . $exception->getMessage());
                    return $this->error(trans('api.NETWORK_ERROR'));
                }
            }
            UserJoin::query()->where([
                'user_id' => $this->user->id,
                'matter_id' => $gameId,
                'type' => 2,
                'status' => 0
            ])->update(['status' => $status]);

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //删除此球员
    public function delPlayer(GameUserRequest $request)
    {
        DB::beginTransaction();
        try {
            $game = Game::query()->find($request->game_id);
            if (!$game) {
                throw new Exception(trans('api.GAME_NOT_EXIST'));
            }
            if (!$this->GameService->hasAuth($this->user->id, $request->game_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $gameUser = GameUser::where('id', $request->game_user_id)->first();
            if (!$gameUser->delete()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            $this->GameService->decMembersCount($request->game_id); //成员数-1
            try {
                $user = User::query()->find($gameUser->user_id);
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $data['member_list'] [] = $user;
                $data['GroupId'] = $game->GroupId;
                $groupService->deleteGroupMember($data);

            } catch (GuzzleException $exception) {
                Log::error('delPlayer：' . $exception->getMessage());
                return $this->error(trans('api.NETWORK_ERROR'));
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //结束比赛
    public function endGame(Request $request)
    {
        DB::beginTransaction();
        try {
            $game = Game::query()->find($request->game_id);
            if (!$game) {
                throw new Exception(trans('api.GAME_NOT_EXIST'));
            }
            if (!$this->GameService->hasAuth($this->user->id, $request->game_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $game = GameModel::find($request->game_id);
            $game->end_time = Carbon::now();
            if (!$game->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            try {
                //解散群聊
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $data['GroupId'] = $game->GroupId;
                $groupService->destroyGroup($data);
            } catch (GuzzleException $exception) {
                Log::error('endGame：' . $exception->getMessage());
                return $this->error(trans('api.NETWORK_ERROR'));
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        Redis::del('ovarallScore'); //删除精彩时刻总杆缓存

        return $this->success();
    }

    //设置比赛权限
    public function setGameAuth(Request $request)
    {
        try {
            if (!$this->GameService->hasAuth($this->user->id, $request->game_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $game = GameModel::find($request->game_id);
            $game->forbid_look = $request->forbid_look ?: 0;
            $game->forbid_join = $request->forbid_join ?: 0;
            if (!$game->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 所有待进行的比赛, 筛除已加入的比赛、用户创建的、已达到比赛人数上限的 比赛
     */
    public function notBegin(Request $request)
    {
        $keyword = $request->input('keyword', '');
        $list = $this->GameService->getNotBeginGames($keyword);

        return $this->success($list);
    }

    //报名比赛（申请比赛）
    public function enteredFor(Request $request, UserJoin $userJoin)
    {
        try {
            $gameId = $request->game_id;
            $userId = $this->user->id;
            $validator = Validator::make($request->all(), [
                'game_id' => 'required|int',
                'reason' => 'max:50',
            ]);
            if ($validator->fails()) {
                throw new Exception($validator->messages()->first());
            }
            if ($this->GameService->isHadJoin($gameId, $userId)) {
                throw new Exception(trans('api.USER_HAD_JOIN'));
            };
            $userJoin->user_id = $userId;
            $userJoin->invitor_id = 0;
            $userJoin->type = 2;
            $userJoin->matter_id = $gameId;
            $userJoin->reason = $request->input('reason', '');
            $userJoin->status = 0; //待审核
            if (!$userJoin->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            $creator = Game::where('id', $gameId)->value('creator');
            //给用户添加消息记录
            $notice = new NoticeService();
            $notice->send_msg($creator, $userJoin->id, 8, $this->user->id, 'api.APPLY_JOIN_GAME', $gameId);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }

    //通过或拒绝
    public function authEntered(Request $request)
    {
        DB::beginTransaction();
        try {
            $userId = $request->user_id;
            $gameId = $request->game_id;
            $status = $request->status;

            $game = Game::query()->where('id', $gameId)->whereNull('deleted_at')->first();
            if (!$game) {
                throw new Exception(trans('api.GAME_NOT_EXIST'));
            }
            if ($this->GameService->isHadJoin($gameId, $userId)) {
                throw new Exception(trans('api.USER_HAD_JOIN'));
            };
            if ($status == 1) { //同意加入后，新增一条记录
                $gameUser = new GameUser();
                $gameUser->user_id = $userId;
                $gameUser->game_id = $gameId;
                $gameUser->type = 1;
                $gameUser->save();
                $this->GameService->incMembersCount($request->game_id); //成员数+1
                try {
                    $groupService = TencentImGroupService::getInstance();
                    $data = array();
                    $user = User::query()->find($userId);
                    $data['member_list'] [] = $user;
                    $data['GroupId'] = $game->GroupId;
                    $groupService->addGroupMember($data);
                } catch (GuzzleException $exception) {
                    Log::error('endGame：' . $exception->getMessage());
                    return $this->error(trans('api.NETWORK_ERROR'));
                }
            }
            UserJoin::query()->where([
                'user_id' => $userId,
                'matter_id' => $gameId,
                'type' => 2,
                'status' => 0
            ])->update(['status' => $status]);

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //报名比赛列表（已提交的）
    public function hadSubmit(Request $request)
    {
        $status = $request->input('status', 1);

        $list = $this->GameService->getHadSubmitGames($status);

        return $this->success($list);
    }

    //围观比赛
    public function lookGame(Request $request)
    {
        try {
            $res = $this->GameService->doLookGame($this->user->id, $request->game_id);
            if ($res) {
                $this->GameService->incLookersCount($request->game_id); //围观数+1
                $user = User::query()->find($this->user->id);
                $game = Game::query()->find($request->game_id);
                try {
                    //邀请用户加入群聊
                    $groupService = TencentImGroupService::getInstance();
                    $data = array();
                    $data['member_list'] [] = $user;
                    $data['GroupId'] = $game->GroupId;
                    $groupService->addGroupMember($data);
                } catch (GuzzleException $exception) {
                    Log::error('lookGame：' . $exception->getMessage());
                    return $this->error(trans('api.NETWORK_ERROR'));
                }
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //围观者列表
    public function onlookers(Request $request)
    {
        $userIds = GameLooker::query()
            ->where('game_id', $request->game_id)
            ->whereNull('deleted_at')
            ->pluck('user_id');

        $list = User::whereIn('id', $userIds)->select('id', 'name', 'avatar', 'is_auth')->get();
        if($list->isEmpty()){
            return [];
        }
        $list = $list->toArray();
        foreach ($list as $key => &$val) {
            $val['have_user_course'] = UserService::haveUserCourse($val['id']);
        }

        return $this->success($list);
    }

    //删除围观者
    public function delLooker(Request $request)
    {
        DB::beginTransaction();
        try {
            $game = Game::query()->find($request->game_id);
            if (!$game) {
                throw new Exception(trans('api.GAME_NOT_EXIST'));
            }
            if (!$this->GameService->delLooker($request->user_id, $request->game_id)) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            $this->GameService->deccLookersCount($request->game_id); //围观数+1
            try {
                //群聊删除用户
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $user = User::query()->find($request->user_id);
                $data['member_list'] [] = $user;
                $data['GroupId'] = $game->GroupId;
                $groupService->deleteGroupMember($data);

            } catch (GuzzleException $exception) {
                Log::error('delLooker：' . $exception->getMessage());
                return $this->error(trans('api.NETWORK_ERROR'));
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //退出比赛
    public function quitGame(Request $request)
    {
        try {
            $gameUser = GameUser::query()
                ->where('status', 1)
                ->where('game_id', $request->game_id)
                ->where('user_id', $this->user->id)
                ->whereNull('deleted_at')
                ->first();

            if (!$gameUser) {
                throw new Exception(trans('api.ILLEGAL_OPERATION'));
            }
            $gameUser->deleted_at = date('Y-m-d H:i:s');
            if (!$gameUser->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            $this->GameService->decMembersCount($request->game_id); //成员数 -1

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //球洞信息
    public function holes(Request $request)
    {
        $gameId = $request->game_id;
        $info = $this->GameService->getHolesInfo($gameId);

        return $this->success($info);
    }

    //正在进行的比赛球员成绩
    public function ongoingGameScores(Request $request)
    {
        $data = $this->GameService->getOngoingGameScores($request->game_id);

        return $this->success($data);
    }

    //比赛计分
    public function setScore(Request $request)
    {
        $gameUserId = $request->input('game_user_id');
        $holeId = $request->input('hole_id');
        $score = $request->input('score'); //球员打的成绩，即实际打的杆数 大于零的整数
        try {
            $this->GameService->changeScore($gameUserId, $holeId, $score);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //球洞成绩
    public function holeScores(Request $request)
    {
        $gameId = $request->game_id;
        $holeId = $request->hole_id;

        //获取比赛的 game_user_ids (真实球手)
        $gameUserIds = GameUser::query()->where(['game_id' => $gameId, 'type' => 1])->pluck('id')->toArray();
        $list1 = $this->GameService->getHoleScores($gameUserIds, $holeId);

        //获取比赛的 fictitious_ids (虚拟球手)
        $fictitiousIds = GameUser::query()->where(['game_id' => $gameId, 'type' => 2])->pluck('id')->toArray();
        $list2 = $this->GameService->getHoleScores2($fictitiousIds, $holeId);

        $list = array_merge($list1, $list2);
        $par = CourseHole::where('id', $holeId)->value('par');

        $data = ['par' => $par, 'list' => $list];

        return $this->success($data);
    }

    //设置 Tee 台
    public function tee(Request $request)
    {
        try {
            $gameUserId = $request->input('game_user_id');
            $level = $request->input('level'); // 4金，3蓝，2白,1红
            $this->GameService->setTee($gameUserId, $level);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //软件内好友
    public function softFriends()
    {
        $list = $this->GameService->getSoftFriends();

        return $this->success($list);
    }

    //添加虚拟球手
    public function addFictitious(StoreFictitious $request, GameUser $gameUser, GameFictitiou $gameFictitiou)
    {
        DB::beginTransaction();
        try {
            if ($request->game_id) { //比赛id,  创建比赛时为0， 已经创建好比赛则必填 game_id
                if (!$this->GameService->isCanAddPlayer($request->game_id)) {
                    throw new Exception(trans('api.MEMBER_HAD_FULL'));
                }
            }
            if (!$id = $this->GameService->addFictitious($request, $gameUser, $gameFictitiou)) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            $this->GameService->incMembersCount($request->game_id); //成员数+1
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success($id);
    }

    //修改人数限制
    public function changeScaleLimit(Request $request)
    {
        try {
            if (!$this->GameService->hasAuth($this->user->id, $request->game_id)) {
                throw  new Exception(trans('api.USER_NO_AUTH'));
            }
            $gameId = $request->game_id;
            $num = $request->num;
            $this->GameService->setScale($gameId, $num);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //精彩时刻 查 game_score_log 即可
    public function wonderfulMoment()
    {
        $list = $this->GameService->getWonderfulMoment();

        return $this->success($list);
    }

    //本场比赛全部球员
    public function getGameUsers(Request $request)
    {
        $gameId = $request->game_id;

        $list = Game::getGameInfo($gameId);

        return $this->success($list);
    }

    //指定球员成绩榜
    public function showScore(Request $request)
    {
        $gameUserId = $request->game_user_id;

        $list = $this->GameService->getGameUserScore($gameUserId);

        return $this->success($list);
    }

    //本场比赛全部球员成绩表
    public function allPlayerScores(Request $request)
    {
        $gameId = $request->game_id;
        $list = $this->GameService->getGameUsers($gameId);

        $result = $this->GameService->getAllScores($list);
        $gameInfo = Game::where('id', $gameId)->select('id as game_id', 'name as game_name', 'begin_time')->first()->toArray();
        $gameInfo['begin_time'] = date('m-d H:i', strtotime($gameInfo['begin_time']));
        $data = [
            'game_info' => $gameInfo,
            'game_users' => $result
        ];
        return $this->success($data);
    }

    //打球纪录
    public function historyGames(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $list = $this->GameService->getHistoryGames($userId);

        return $this->success($list);
    }

    //球员指定比赛的成绩
    public function gameScore(Request $request)
    {
        $list = $this->GameService->getGameScore($request->game_id, $request->user_id);

        return $this->success($list);
    }

    //月最佳总杆
    public function monthBestPar(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $gameMonths = $this->GameService->getGameMonth($userId);
        if (empty($gameMonths)) {
            return $this->success($gameMonths);
        }
        $months = array_column($gameMonths, 'month');
        $list = [];
        $months = array_unique($months);
        foreach ($months as $month) {
            $list[] = $this->GameService->getMonthBestScore($month, $userId);
        }
        $list = array_values(array_filter($list));

        return $this->success($list);
    }

    //历史最佳总杆
    public function historyBestPar()
    {
        $user = auth('api')->user();
        $gameMonths = $this->GameService->getGameMonth($user->id);
        if (empty($gameMonths)) {
            return $this->success($gameMonths);
        }
        $months = array_column($gameMonths, 'month');
        $list = [];
        $months = array_unique($months);

        foreach ($months as $month) {
            $list[] = $this->GameService->getMonthBestScore($month, $user->id);
        }
        $list = array_values(array_filter($list));

        $sort_key = array_column($list, 'total_score');

        array_multisort($sort_key, SORT_ASC, $list);

        $best = array_shift($list);

        return $this->success($best);
    }

    //打过的球场
    public function historyCourses(Request $request)
    {
        $page   = $request->input('page', 1);
        $userId = $request->input('user_id', 0);

        $list = $this->GameService->getHistoryCourses($page);

        return $this->success($list);
    }

    //球场比赛统计
    public function courseGames(Request $request)
    {
        $limit = $request->query('limit', 15);
        $offset = $request->query('offset', 0);

        $data = $this->GameService->getCourseGames($request->course_id, $offset, $limit);

        return $this->success($data);
    }

    //用户是否已加入比赛
    public function isHadJoin(Request $request)
    {
        $gameId = $request->input('game_id');
        $userId = $request->input('user_id');

        if ($this->GameService->isHadJoin($gameId, $userId)) {
            $isHadJoin = 1;
        } else {
            $isHadJoin = 0;
        }
        $data = [
            'is_had_join' => $isHadJoin,
        ];

        return $this->success($data);
    }


}
