<?php


namespace App\Http\Controllers\V1;

use App\Exceptions\TencentImException;
use App\Models\ChatTeam;
use App\Models\User;
use App\Services\Api\UserService;
use App\Services\TencentImGroupService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;
use Illuminate\Support\Facades\Log;

class ChatTeamController extends Controller
{
    private $groupService;

    public function __construct()
    {
        parent::__construct();
        $this->groupService = TencentImGroupService::getInstance();;
        $this->user = auth('api')->user();
    }

    //创建群聊
    public function createGroup(Request $request)
    {
        try {
            DB::beginTransaction();
            $user = $this->user;
            $ids = $request->ids;
            if (empty($ids) || !is_array($ids)) {
                throw new Exception(trans('api.PARAMS_ERROR'));
            }
            $group_name = 'Group';  //组装群名
            $data = $this->groupService->getUsersAndAvatar($ids); //获取群头像和 users

            $group_info['group_name'] = $group_name;
            $group_info['Owner_Account'] = $user->tencent_im_user_id;
            $group_info['member_list'] = $data['users'];
            $group_info['avatar'] = $data['file_avatar'];
            $res = $this->groupService->createGroup($group_info);

            $chatTeam = new ChatTeam();
            $chatTeam->user_id = $user->id;
            $chatTeam->Owner_Account = $user->tencent_im_user_id;
            $chatTeam->group_name = $group_name;
            $chatTeam->GroupId = $res['GroupId'];
            $chatTeam->FaceUrl = $data['file_avatar'];
            $chatTeam->MaxMemberCount = 20;
            $chatTeam->ApplyJoinOption = 'FreeAccess';
            $chatTeam->type = 1;
            $chatTeam->save();

            //发一条群公告，目的是为了让群自动发一条消息
            $initData['GroupId'] = $res['GroupId'];
            $initData['Introduction'] = 'Hello everyone!, Welcome to join us!';
            $this->groupService->modifyGroupBaseInfo($initData);

            DB::commit();
        } catch (GuzzleException $e) {
            DB::rollBack();
            Log::error('创建群聊:GuzzleException：' . $e->getMessage());

            return $this->error(trans('api.NETWORK_ERROR'));
        }

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

    //获取用户群聊列表
    public function getUserGroup()
    {
        try {
            $user = $this->user;
            $data['tencent_im_user_id'] = $user->tencent_im_user_id;
            $res = $this->groupService->getJoinedGroupList($data);
        } catch (GuzzleException $e) {
            Log::error('获取用户群聊列表：' . $e->getMessage());
            return $this->error(trans('api.NETWORK_ERROR'));
        }

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

    //获取群聊详细信息
    public function getGroupInfo(Request $request)
    {
        try {
            $groupId = $request->group_id;
            if (!$chatTeam = ChatTeam::query()->where(['GroupId' => $groupId])->first()) {
                throw new \Exception(trans('api.GROUP_CHAT_DOES_NOT_EXIST'));
            }
            $res = $this->groupService->getGroupInfo($groupId);
            $res['type'] = $chatTeam->type ?: 1;
            if ($res['ErrorCode'] == 0 && !empty($res['GroupInfo'])) {
                if (!empty($res['GroupInfo'][0]['MemberList'])) {
                    foreach ($res['GroupInfo'][0]['MemberList'] as &$v) {
                        $user = User::query()->where('tencent_im_user_id', $v['Member_Account'])->select('id', 'name', 'avatar', 'is_auth')->first();
                        $v['user_id'] = $user->id;
                        $v['name']    = $user->name;
                        $v['avatar']  = $user->avatar;
                        $v['is_auth'] = $user->is_auth;
                        $v['have_user_course'] = UserService::haveUserCourse($user->id);
                    }
                }
            }
        } catch (GuzzleException $e) {
            return $this->error(trans('api.NETWORK_ERROR'));
        }
        return $this->success($res);
    }

    //修改群名称
    public function updateGroupName(Request $request)
    {
        try {
            $user = $this->user;
            $groupId = $request->group_id;
            $group_name = $request->group_name;
            if (empty($group_name)) {
                throw new Exception(trans('api.GROUP_NAME_NOT_NULL'));
            }
            if (!$chatTeam = $this->isGroupExist($groupId)) {
                throw new Exception(trans('api.GROUP_CHAT_DOES_NOT_EXIST'));
            }
            if (!$this->isHasActionAuth($user, $chatTeam)) {
                throw new Exception(trans('api.UNAUTHORIZED_OPERATION'));
            }

            $data['GroupId'] = $groupId;
            $data['name'] = $group_name;
            $res = $this->groupService->modifyGroupBaseInfo($data);
            //修改本地数据
            $chatTeam->group_name = $group_name;
            $chatTeam->save();

        } catch (GuzzleException $e) {
            Log::error('修改群名称：' . $e->getMessage());
            return $this->error(trans('api.NETWORK_ERROR'));
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }

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

    //退出群聊 (成员)
    public function quitGroup(Request $request)
    {
        try {
            $user = $this->user;
            $groupId = $request->group_id;
            $this->isGroupExist($groupId);

            $data['GroupId'] = $groupId;
            $data['member_list'] [] = $user;
            $this->groupService->deleteGroupMember($data);

        } catch (GuzzleException $e) {
            Log::error('退出群聊：' . $e->getMessage());
            return $this->error(trans('api.NETWORK_ERROR'));
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //添加群成员
    public function addGroupUsers(Request $request)
    {
        try {
            $user = $this->user;
            $ids = $request->ids;
            if (empty($ids) || !is_array($ids)) {
                return $this->error(trans('api.PARAMS_ERROR'));
            }

            $groupId = $request->group_id;
            if (!$chatTeam = $this->isGroupExist($groupId)) {
                throw new Exception(trans('api.GROUP_CHAT_DOES_NOT_EXIST'));
            }
            if (!$this->isHasActionAuth($user, $chatTeam)) {
                throw new Exception(trans('api.UNAUTHORIZED_OPERATION'));
            }

            $users = User::query()->whereIn('id', $ids)
                ->select(['id', 'name', 'avatar', 'tencent_im_user_id'])
                ->get()->toArray();

            $data['GroupId'] = $groupId;
            $data['member_list'] = $users;
            $this->groupService->addGroupMember($data);

        } catch (GuzzleException $e) {
            Log::error('添加群成员：' . $e->getMessage());
            return $this->error(trans('api.NETWORK_ERROR'));
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //删除群成员
    public function delGroupUsers(Request $request)
    {
        try {
            $user = $this->user;
            $ids = $request->ids;
            if (empty($ids) || !is_array($ids)) {
                return $this->error(trans('api.PARAMS_ERROR'));
            }
            $groupId = $request->group_id;

            if (!$chatTeam = $this->isGroupExist($groupId)) {
                throw new Exception(trans('api.GROUP_CHAT_DOES_NOT_EXIST'));
            }
            if (!$this->isHasActionAuth($user, $chatTeam)) {
                throw new Exception(trans('api.UNAUTHORIZED_OPERATION'));
            }

            $users = User::query()
                ->whereIn('id', $ids)
                ->select(['id', 'name', 'avatar', 'tencent_im_user_id'])
                ->get()
                ->toArray();

            $data['GroupId'] = $groupId;
            $data['member_list'] = $users;
            $this->groupService->deleteGroupMember($data);

        } catch (GuzzleException $e) {
            Log::error('删除群成员:' . $e->getMessage());
            return $this->error(trans('api.NETWORK_ERROR'));
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //群主转让
    public function changeGroupOwner(Request $request)
    {
        try {
            DB::beginTransaction();
            $user = $this->user;
            $groupId = $request->group_id;

            if (!$chatTeam = $this->isGroupExist($groupId)) {
                throw new Exception(trans('api.GROUP_CHAT_DOES_NOT_EXIST'));
            }
            if (!$this->isHasActionAuth($user, $chatTeam)) {
                throw new Exception(trans('api.UNAUTHORIZED_OPERATION'));
            }

            $new_user_id = $request->user_id;
            $new_user = User::query()->find($new_user_id);
            $data['GroupId'] = $groupId;
            $data['tencent_im_user_id'] = $new_user->tencent_im_user_id;
            $this->groupService->changeGroupOwner($data);

            $chatTeam->Owner_Account = $new_user->tencent_im_user_id;
            $chatTeam->save();
            DB::commit();

        } catch (GuzzleException $e) {
            DB::rollBack();
            Log::error('删除群成员:' . $e->getMessage());
            return $this->error(trans('api.NETWORK_ERROR'));

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

        return $this->success();
    }

    //解散群
    public function destroyGroup(Request $request)
    {
        try {
            $user = $this->user;
            $groupId = $request->group_id;

            if (!$chatTeam = $this->isGroupExist($groupId)) {
                throw new Exception(trans('api.GROUP_CHAT_DOES_NOT_EXIST'));
            }
            if (!$this->isHasActionAuth($user, $chatTeam)) {
                throw new Exception(trans('api.UNAUTHORIZED_OPERATION'));
            }

            $chatTeam->deleted_at = date('Y-m-d H:i:s');
            $chatTeam->save();
            $data['GroupId'] = $groupId;
            $this->groupService->destroyGroup($data);

        } catch (GuzzleException $e) {
            Log::error('解散群:' . $e->getMessage());
            return $this->error(trans('api.NETWORK_ERROR'));
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //判断群聊是否已删除
    public function isGroupExist($groupId)
    {
        $chatTeam = ChatTeam::query()
            ->where('GroupId', $groupId)
            ->whereNull('deleted_at')
            ->first();

        if (!$chatTeam) {
            return false;
        }
        return $chatTeam;
    }

    //判断群聊是有操作权限
    public function isHasActionAuth($user, $chatTeam)
    {
        if ($user->tencent_im_user_id != $chatTeam->Owner_Account) {
            return false;
        }
        return true;
    }


}
