<?php

namespace App\Http\Controllers\V1;

use App\Http\Requests\StoreTeam;
use App\Models\ChatTeam;
use App\Models\Team;
use App\Models\Team as TeamModel;
use App\Models\TeamPhoto;
use App\Models\TeamUser;
use App\Models\User;
use App\Models\UserJoin;
use App\Services\Api\UserService;
use App\Services\JPushService;
use App\Services\Api\NoticeService;
use App\Services\Api\TeamService;
use App\Services\TencentImGroupService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Util\Exception;
use GuzzleHttp\Exception\GuzzleException;

class TeamController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->user = auth('api')->user();
        $this->TeamService = new TeamService();
        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(StoreTeam $request, TeamModel $team)
    {
        try {
            if (!$info = $this->TeamService->isCanCreateTeam()) {
                throw new Exception(trans('api.YOU_HAVE_A_TEAM_ALREADY'));
            }
            DB::beginTransaction();
            //保存球队信息
            $team->name = $request->name;
            $team->address = $request->address;
            $team->member_counts = $request->member_counts; //球队人数上限
            $team->slogan = $request->slogan;
            $team->desc = $request->desc;
            $team->creator = $this->user->id;
            $team->set_date = $request->set_date;
            $team->allow_join = 1;
            $team->img = $request->img;
            $team->cover_img = '';

            try {
                //创建群聊
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $data['member_list'] [] = $this->user;
                $data['Owner_Account'] = $this->user->tencent_im_user_id;
                $data['group_name'] = $request->name;
                $data['avatar'] = $request->img;
                $groupResult = $groupService->createGroup($data);
                if ($groupResult['ActionStatus'] == 'OK' && $groupResult['ErrorCode'] == 0) {
                    $team->GroupId = $groupResult['GroupId'];
                }
            } catch (GuzzleException $exception) {
                Log::error('创建球队：' . $exception->getMessage());
                return $this->error(trans('api.NETWORK_ERROR'));
            }

            $chatTeam = new ChatTeam();
            $chatTeam->user_id = $this->user->id;
            $chatTeam->Owner_Account = $this->user->tencent_im_user_id;
            $chatTeam->group_name = $request->name;
            $chatTeam->GroupId = $groupResult['GroupId'];
            $chatTeam->FaceUrl = $request->img;
            $chatTeam->MaxMemberCount = 20;
            $chatTeam->ApplyJoinOption = 'FreeAccess';
            $chatTeam->type = 2;
            $chatTeam->save();
            if (!$team->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            //保存球队人员
            $teamUser = new TeamUser();
            $teamUser->user_id = $this->user->id;
            $teamUser->team_id = $team->id;
            $teamUser->save();
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

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

    //球队详情
    public function detail(Request $request)
    {
        $teamId = $request->input('id');

        $team = TeamModel::where('id', $teamId)->first();
        if(empty($team)){
            return $this->success([]);
        }
        $team = $team->toArray();
        $user = User::where('id', $team['creator'])->select('id', 'name', 'bio', 'sex', 'avatar', 'birthday', 'is_auth')->first();
        $user['have_user_course'] = UserService::haveUserCourse($user->id);
        $team['creator_info'] = $user;

        if (auth('api')->user()) {
            $team['is_team_user'] = $this->TeamService->isTeamUser($teamId) ? 1 : 0;
            $team['apply_info'] = $this->TeamService->isUserHadApplyJoin($teamId, $this->user->id);
            $team['invite_info'] = $this->TeamService->isUserHadInvitedJoin($teamId, $this->user->id);
        }

        $team['actual_member_counts'] = $this->TeamService->getTeamUserCount($teamId);

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

    //编辑球队
    public function update(StoreTeam $request)
    {
        try {
            if (!$request->id) {
                throw new Exception(trans('api.PARAMS_ERROR'));
            }
            if (!self::hasAuth($request->id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $team = TeamModel::find($request->id);
            $preName = $team->name;
            $actualCount = TeamService::getTeamUserCount($request->id);

            if($request->member_counts < $actualCount){
                throw new Exception(trans('api.MEMBER_COUNT_IllEGAL'));
            }
            $teamName = $request->name;
            $team->name = $teamName;
            $team->address = $request->address;
            $team->member_counts = $request->member_counts; //人数上限
            $team->slogan = $request->slogan;
            $team->desc = $request->desc;
            $team->creator = $this->user->id;
            $team->set_date = $request->set_date;
            $team->allow_join = 1;
            $team->img = $request->img;
            if (!$team->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }

            if($teamName != $preName){ //如果群聊名称发生改变，更新群聊名称
                $groupData['GroupId'] = $team->GroupId;
                $groupData['name'] = $teamName;
                $groupService = TencentImGroupService::getInstance();
                $groupService->modifyGroupBaseInfo($groupData);
                //修改本地数据
                $chatTeam = ChatTeam::query()
                    ->where('GroupId', $team->GroupId)
                    ->whereNull('deleted_at')
                    ->first();
                $chatTeam->group_name = $teamName;
                $chatTeam->save();
            }

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

        return $this->success();
    }

    //添加成员
    public function addMember(Request $request, TeamUser $teamUser)
    {
        try {
            $teamId = $request->team_id;
            $userId = $request->user_id;

            if (!self::hasAuth($teamId)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $validator = Validator::make($request->all(), [
                'team_id' => 'required|numeric',
                'user_id' => 'required|numeric',
            ]);
            if ($validator->fails()) {
                throw new Exception($validator->messages()->first());
            }
            if ($teamUser::query()->where(['user_id' => $userId, 'team_id' => $teamId])->first()) {
                throw new Exception(trans('api.ILLEGAL_OPERATION'));
            };
            $teamUser->team_id = $teamId;
            $teamUser->user_id = $userId;
            if (!$teamUser->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //球队成员
    public function members(Request $request)
    {
        $data = $this->TeamService->getTeamMembers($request->team_id);

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

    //我的球队
    public function myTeams(Request $request)
    {
        $userId = $request->input('user_id', 0);
        $list = $this->TeamService->getMyTeams($userId);
        $can = $this->TeamService->isCanCreateTeam();

        $data = [
            'is_can_create_new' => $can ? 1 : 0,
            'list' => $list
        ];

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

    //退出球队
    public function exitTeam(Request $request, TeamUser $teamUser)
    {
        try {
            $teamId = $request->team_id;
            $userId = $request->user_id;

            DB::beginTransaction();
            $validator = Validator::make($request->all(), [
                'team_id' => 'required|numeric',
                'user_id' => 'required|numeric',
            ]);
            if ($validator->fails()) {
                throw new Exception($validator->messages()->first());
            }
            $joinUser = User::query()->find($userId);
            if (!$joinUser) {
                throw new Exception(trans('api.NOT_EXIST'));
            }
            $team = Team::query()->find($teamId);
            if (!$team) {
                throw new Exception(trans('api.TEAM_NOT_EXIST'));
            }
            $map = [
                'user_id' => $userId,
                'team_id' => $teamId,
            ];
            if (!$teamUser::query()->where($map)->delete()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            try {
                //群聊删除用户
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $data['member_list'] [] = $joinUser;
                $data['GroupId'] = $team->GroupId;
                $groupService->deleteGroupMember($data);
            } catch (GuzzleException $exception) {
                Log::error('exitTeam：' . $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 delMember(Request $request)
    {
        try {
            $teamId = $request->team_id;
            $userId = $request->user_id;

            DB::beginTransaction();
            if (!self::hasAuth($teamId)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $joinUser = User::query()->find($userId);
            if (!$joinUser) {
                throw new Exception(trans('api.NOT_EXIST'));
            }
            $team = Team::query()->whereNull('deleted_at')->find($teamId);
            if (!$team) {
                throw new Exception(trans('api.TEAM_NOT_EXIST'));
            }
            $map1 = [
                'user_id' => $userId,
                'matter_id' => $teamId,
                'type' => 1
            ];
            $map2 = [
                'user_id' => $userId,
                'team_id' => $teamId,
            ];
            $res1 = UserJoin::query()->where($map1)->delete();
            $res2 = TeamUser::query()->where($map2)->delete();

            if (!$res1 || !$res2) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            try {
                //群聊删除用户
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $data['member_list'] [] = $joinUser;
                $data['GroupId'] = $team->GroupId;
                $groupService->deleteGroupMember($data);

            } catch (GuzzleException $exception) {
                Log::error('delMember：' . $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 searchMember(Request $request)
    {
        $keyword = $request->keyword;
        $teamId = $request->team_id;

        $list = TeamUser::query()
            ->leftJoin('users as u', 'u.id', '=', 'team_users.user_id')
            ->where('team_users.team_id', '=', $teamId)
            ->where('u.name', 'like', '%' . $keyword . '%')
            ->orWhere('u.id', $keyword)
            ->select('u.id', 'u.name', 'u.avatar', 'u.is_auth')
            ->get();

        if(empty($list)){
            return $this->success([]);
        }
        $list = $list->toArray();
        foreach ($list as $key => &$val) {
            $val['have_user_course'] = UserService::haveUserCourse($val['id']);
        }

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

    //搜索球队
    public function searchTeams(Request $request)
    {
        $keyword = $request->keyword;

        $list = TeamModel::query()
            ->whereNull('deleted_at')
            ->where('name', 'like', '%' . $keyword . '%')
            ->orWhere('id', $keyword)
            ->select('*')
            ->orderBy('id')
            ->limit(20)
            ->get();

        if($list->isEmpty()){
            return $this->success([]);
        }
        $list = $list->toArray();
        foreach ($list as $key => $val) {
            $val['actual_member_counts'] = $this->TeamService->getTeamUserCount($val['id']);
            $list[$key] = $val;
        }

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

    //申请加入
    public function applyJoin(Request $request, UserJoin $userJoin)
    {
        DB::beginTransaction();
        try {
            $teamId = $request->team_id;
            $team = Team::query()->find($teamId);
            if (!$team) {
                throw new Exception(trans('api.TEAM_NOT_EXIST'));
            }
            if ($this->TeamService->isHadJoin($teamId, $this->user->id)) {
                throw new Exception(trans('api.USER_HAD_JOIN'));
            }
            $userJoin->user_id = $this->user->id;
            $userJoin->invitor_id = 0; //邀请人为 0
            $userJoin->matter_id = $teamId;
            $userJoin->type = 1; //1球队,2比赛
            $userJoin->status = 0; //待确认
            $userJoin->reason = $request->input('reason', '');

            if (!$userJoin->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            //给球队管理者添加消息记录
            $notice = new NoticeService();
            $notice->send_msg($team['creator'], $userJoin->id, 6, $this->user->id, 'api.APPLY_JOIN_TEAM', $teamId);

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

    //邀请加入球队
    public function inviteJoin(Request $request, UserJoin $userJoin)
    {
        DB::beginTransaction();
        try {
            $teamId = $request->team_id; //球队
            $userId = $request->user_id; //被邀请人

            if ($this->user->id == $userId) {
                throw new Exception(trans('api.ILLEGAL_OPERATION'));
            }
            if ($this->TeamService->isHadJoin($teamId, $userId)) {
                throw new Exception(trans('api.USER_HAD_JOIN'));
            }
            $userJoin->user_id = $userId;
            $userJoin->invitor_id = $this->user->id;//邀请人
            $userJoin->matter_id = $teamId;
            $userJoin->type = 1; //1球队, 2比赛
            $userJoin->status = 0; //待确认
            $userJoin->reason = $request->input('reason', '');
            if (!$userJoin->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            //给用户添加消息记录
            $notice = new NoticeService();
            $notice->send_msg($userId, $userJoin->id, 5, $this->user->id, 'api.INVITE_JOIN_TEAM', $teamId);

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

    //同意或拒绝加入
    public function join(Request $request)
    {
        DB::beginTransaction();
        try {
            $teamId = $request->team_id;
            $userId = $request->user_id;

            $user = User::query()->where('id', $userId)->whereNull('deleted_at')->first();
            if (!$user) {
                throw new Exception(trans('api.NOT_EXIST'));
            }
            $team = Team::query()->where('id', $teamId)->whereNull('deleted_at')->first();
            if (!$team) {
                throw new Exception(trans('api.TEAM_NOT_EXIST'));
            }
            if ($this->TeamService->isHadJoin($teamId, $userId)) {
                throw new Exception(trans('api.USER_HAD_JOIN'));
            }
            if ($request->status == 1) {
                //同意加入后，新增一条记录
                $teamUser = new TeamUser();
                $teamUser->team_id = $teamId;
                $teamUser->user_id = $userId;
                if (!$teamUser->save()) {
                    throw new Exception(trans('api.DATA_SAVE_FALSE'));
                }
                try {
                    //邀请用户加入群聊
                    $groupService = TencentImGroupService::getInstance();
                    $data = array();
                    $data['member_list'] [] = $user;
                    $data['GroupId'] = $team->GroupId;
                    $groupService->addGroupMember($data);
                } catch (GuzzleException $exception) {
                    Log::error('同意或拒绝加入球队join：' . $exception->getMessage());
                    return $this->error(trans('api.NETWORK_ERROR'));
                }
            }
            UserJoin::query()->where([
                'user_id' => $userId,
                'matter_id' => $teamId,
                'type' => 1,
                'status' => 0,
            ])->update(['status' => $request->status]);

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

        return $this->success();
    }

    //只有创建者才可以操作
    public function hasAuth($teamId)
    {
        $user_id = $this->user->id;
        $where = ['id' => $teamId, 'creator' => $user_id];
        if (!$info = TeamModel::query()->where($where)->first()) {
            return false;
        }
        return true;
    }

    //修改球队背景图
    public function background(Request $request)
    {
        try {
            if (!self::hasAuth($request->team_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $team = TeamModel::find($request->team_id);
            $team->cover_img = $request->cover_img;
            if (!$team->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //发布公告
    public function publishNotice(Request $request)
    {
        try {
            if (!self::hasAuth($request->team_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $team = TeamModel::find($request->team_id);
            $team->notice = $request->notice;
            $team->notice_time = date('Y-m-d H:i:s');
            if (!$team->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //获取公告
    public function getNotice(Request $request)
    {
        $team = TeamModel::find($request->team_id);
        if (!empty($team['notice'])) {
            $data = [
                'notice' => $team['notice'],
                'notice_time' => date('Y-m-d H:i', strtotime($team['notice_time'])),
            ];
        } else {
            $data = ['notice' => '', 'notice_time' => ''];
        }

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

    //发布相册
    public function publishPhotos(Request $request, TeamPhoto $teamPhoto)
    {
        try {
            if (!$this->TeamService->isTeamUser($request->team_id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $teamPhoto->user_id = $this->user->id;
            $teamPhoto->team_id = $request->team_id;
            $photo_urls = $request->input('photo_urls');
            if (!empty($photo_urls) && is_array($photo_urls)) {
                $photo_arr = array();
                foreach ($photo_urls as $k => $v) {
                    $photo_arr [] = array('url' => $v);
                }
            } else {
                $photo_arr = [];
            }
            $teamPhoto->photo_urls = json_encode($photo_arr);
            if (!$teamPhoto->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //获取球队相册
    public function getPhotos(Request $request)
    {
        $teamId = $request->input('team_id');
        $userId = $request->input('user_id', '');

        $list = $this->TeamService->getTeamPhotos($teamId, $userId);

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

    //删除相册
    public function delPhoto(Request $request)
    {
        try {
            if (!$this->TeamService->isHasAuthDel($request->id)) {
                throw new Exception(trans('api.USER_NO_AUTH'));
            }
            $teamPhoto = TeamPhoto::find($request->id);
            $teamPhoto->is_delete = 1;
            if (!$teamPhoto->save()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

    //球队比赛，经过认证的用户创建的比赛
    public function games(Request $request)
    {
        $list = $this->TeamService->getTeamGames($request->team_id);

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

    //解散球队
    public function dismiss(Request $request)
    {
        try {
            DB::beginTransaction();
            $team = TeamModel::find($request->team_id);
            if (!$team) {
                throw new Exception(trans('api.TEAM_NOT_EXIST'));
            }
            if (!$team->delete()) {
                throw new Exception(trans('api.DATA_SAVE_FALSE'));
            }
            try {
                //解散群聊
                $groupService = TencentImGroupService::getInstance();
                $data = array();
                $data['GroupId'] = $team->GroupId;
                $groupService->destroyGroup($data);
            } catch (GuzzleException $exception) {
                Log::error('dismiss：' . $exception->getMessage());
                return $this->error(trans('api.NETWORK_ERROR'));
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success();
    }

}
