<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Models\Collaborator;
use App\Models\DmaServiceUserRole;
use App\Models\Group;
use App\Models\GroupMessage;
use App\Models\GroupUser;
use App\Models\Order;
use App\Models\ServiceRole;
use App\Models\ServiceRoleUser;
use App\Models\User;
use App\Models\WangYiYun;
use cccdl\yunxin_sdk\Im\Msg;
use cccdl\yunxin_sdk\Im\Team;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use mysql_xdevapi\Exception;

class ChatController extends Controller
{
    public function chatMessages(Request $request, Order $order)
    {
        $group = $order->group;
        $group_users = GroupUser::where('group_id', $group->id)->get();
        $messages = GroupMessage::with('user')->where('group_id', $group->id)->orderByDesc('id')->paginate();
        foreach ($messages as $message) {
            $role = $group_users->where('user_id', $message->user_id)->first();
            $message->role_name = $role ? $role->role_name : '';
        }
        return $this->success('ok', compact('group', 'messages'));
    }

    /**
     * 绑定订单和企业群
     * @param Request $request
     * @param Order $order
     */
    public function bindOrderChat(Request $request, Order $order)
    {
        $chat_id = $request->input('chat_id');
        $chat_name = $request->input('chat_name');
        if (empty($chat_id))
            throw new \Exception('缺少企业微信群id');
        $bind_group = Group::where('chat_id', $chat_id)->first();
        $group = $order->group;
        if ($bind_group && $bind_group->id != $group->id)
            return $this->failure("该企业群已绑定订单");
        $group->chat_id = $chat_id;
        $group->chat_name = $chat_name;
        $group->save();

        //操作记录
        OperationLoggedEvent::dispatch("给订单:$order->id 绑定了企业微信群: $chat_id");
        return $this->success('ok');
    }

    public function workChats(Request $request)
    {
        $limit = $request->input('limit', 15);
        $cursor = $request->input('course', '');
        $res = WechatService::groupChats($cursor, $limit);
        $chats = $res->group_chat_list;
        $next_cursor = $res->next_cursor ?? '';
        $group_chats = [];
        foreach ($chats as $chat) {
            $group_chats[] = WechatService::groupChat($chat->chat_id);
        }
        return $this->success('ok', compact('group_chats', 'next_cursor'));
    }


    /**
     * 获取网易云用户
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getWangYiYunUser(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $no_page = $request->get('no_page');
            $is_service = $request->get('is_service');
            if ($is_service) {
                $query = User::query()->whereHas("damServiceUserRole", function ($sql) {
                    $sql/*->whereIn("role", [1, 2, 3])*/ ->where('status', 1);
                })->when($keyword, function ($query) use ($keyword) {
                    $query->where(function ($query) use ($keyword) {
                        $query->where('name', 'like', "%{$keyword}%")->orWhere('mobile', 'like', "%{$keyword}%");
                        $mobileStr = aesEncryptCBC($keyword);
                        if ($mobileStr) {
                            $query->orWhere("mobile", $mobileStr);
                        }
                    });
                })
                    ->orderByDesc('id');
            } else {
                $query = User::query()->whereIn('source', [1, 4])->when($keyword, function ($query) use ($keyword) {
                    $query->where(function ($query) use ($keyword) {
                        $query->where('name', 'like', "%{$keyword}%")->orWhere('mobile', 'like', "%{$keyword}%");
                        $mobileStr = aesEncryptCBC($keyword);
                        if ($mobileStr) {
                            $query->orWhere("mobile", $mobileStr);
                        }
                    });
                })
                    ->orderByDesc('id');
            }
            if ($no_page) {
                $list = $query->get();
            } else {
                $list = $query->paginate();
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            Log::error('getWangYiYunUser:' . $e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 后台创建群聊
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function createGroup(Request $request)
    {
        DB::beginTransaction();
        try {
            $data = $request->all();
            $validated = Validator::make($data, [
                'name' => 'required', // 数组群名称必填
                'msg' => 'required', // 邀请发送的文字必填
                'agree' => 'required',
                'owner_id' => 'required', // 群主必填
                'icon' => 'required', // 群头像必填
                'intro' => 'required', // 群描述必填
                'announcement' => 'required', // 群公告必填
                'join_mode' => 'required', // 加入方式必填
//                'user_ids' => 'required', // 群成员必填
                'order_id' => 'required', // 订单必填
            ], [
                'name.required' => '请填写群名称',
                'agree.required' => '请选择进群方式',
                'msg.required' => '请填写邀请文字',
                'owner_id.required' => '请选择群主',
                'icon.required' => '请上传群头像',
                'intro.required' => '请输入群描述',
                'announcement.required' => '请输入群公告',
                'join_mode.required' => '请选择加入方式',
                //                'user_ids.required' => '请选择群成员',
                'order_id.required' => '请选择订单',
            ]);

            //            $exists = Group::where('order_id',$data['order_id'])->exists();
//            if($exists){
//                return $this->failure('订单已绑定群组,请勿重复绑定');
//            }

            if ($validated->fails()) {
                // 验证失败，返回错误信息
                $errors = $validated->errors()->all();
                $error = count($errors) ? $errors[0] : null;
                // 处理错误信息的逻辑
                return $this->failure($error);
            }

            //生成规则都是一样的,这里就不查数据库了
            $owner_ac_cid = make_wangyiyun_accid($data['owner_id']);


            $options = [];
            $options['icon'] = $data['icon'];
            $options['intro'] = $data['intro'];
            $options['announcement'] = $data['announcement'];
            //创建群,并插入群成员
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $group_info = $imTeam->create($data['name'], $owner_ac_cid, [], $data['msg'], $data['agree'], $data['join_mode'], $options);

            //如果该订单号存在群组,则修改群信息
            $group_exists = Group::where('order_id', $data['order_id'])->first();
            $group_model = [];
            if ($group_exists) {
                if (!$group_exists->im_chat_id) {
                    //修改群信息
                    $group_exists->name = $data['name'];
                    $group_exists->avatar = $data['icon'];
                    $group_exists->intro = $data['intro'];
                    $group_exists->announcement = $data['announcement'];
                    $group_exists->owner_id = $data['owner_id'];
                    $group_exists->chat_name = $data['name'];
                    $group_exists->im_chat_id = $group_info['tid'];
                    $group_exists->save();

                    //插入群主到群成员表
                    GroupUser::create(['user_id' => $data['owner_id'], 'group_id' => $group_exists->id, 'type' => GroupUser::TYPE_OWNER]);
                }
            } else {
                //创建群
                $map = [];
                $map['name'] = $data['name'];
                $map['order_id'] = $data['order_id'];
                $map['avatar'] = $data['icon'];
                $map['intro'] = $data['intro'];
                $map['announcement'] = $data['announcement'];
                $map['owner_id'] = $data['owner_id'];
                $map['chat_name'] = $data['name'];
                $map['im_chat_id'] = $group_info['tid'];
                $map['type'] = Group::TYPE_WANGYIYUN;
                $group_model = Group::create($map);

                //插入群主到群成员表
                GroupUser::create(['user_id' => $data['owner_id'], 'group_id' => $group_model->id, 'type' => GroupUser::TYPE_OWNER]);

                //发送群消息
                $owner_ac_cid = make_wangyiyun_accid($data['owner_id']);
                $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));

                $imMsg->sendMsg($owner_ac_cid, 1, $group_info['tid'], 0, json_encode(['msg' => '友福健康，诚心为您服务']));
            }

            //插入群成员
//            $group_user_map = [];
//            $group_user_map['group_id'] = $group_model->id;
//            foreach ($data['user_ids'] as $val){
//                $group_user_map['user_id'] = $val;
//                GroupUser::create($group_user_map);
//            }
            DB::commit();
            return $this->success('ok', $group_model);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('createGroup:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 修改群信息
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateGroupInfo(Request $request)
    {
        DB::beginTransaction();
        try {
            $data = $request->all();
            $validated = Validator::make($data, [
                'group_id' => 'required', // 数组群名称必填
                'name' => 'required', // 数组群名称必填
//                'icon' => 'required', // 群头像必填
                'intro' => 'required', // 群描述必填
                'announcement' => 'required', // 群公告必填
                'order_id' => 'required', // 订单必填
                'owner_id' => 'required', // 群主id
            ], [
                'group_id.required' => '请选择群组',
                'name.required' => '请填写群名称',
                //                'icon.required' => '请上传群头像',
                'intro.required' => '请输入群描述',
                'announcement.required' => '请输入群公告',
                'order_id.required' => '请选择订单',
                'owner_id.required' => '请选择群主',
            ]);

            $group = Group::where('id', $data['group_id'])->first();
            if (!$group) {
                return $this->failure('群组不存在');
            }

            $exists = Group::where('order_id', $data['order_id'])->exists();

            if ($exists && $group->order_id != $data['order_id']) {
                return $this->failure('订单已绑定群组,请勿重复绑定');
            }

            if ($validated->fails()) {
                // 验证失败，返回错误信息
                $errors = $validated->errors()->all();
                $error = count($errors) ? $errors[0] : null;
                // 处理错误信息的逻辑
                return $this->failure($error);
            }


            //生成规则都是一样的,这里就不查数据库了
            $owner_ac_cid = make_wangyiyun_accid($group->owner_id);

            //修改群资料
            $options = [];
            $options['tname'] = $data['name'];
            $options['icon'] = $data['icon'];
            $options['announcement'] = $data['announcement'];
            $options['intro'] = $data['intro'];

            //创建群,并插入群成员
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->update($group->im_chat_id, $owner_ac_cid, $options);

            if ($group->owner_id != $data['owner_id']) {
                $old_owner_ac_cid = make_wangyiyun_accid($group->owner_id);
                $new_owner_id = make_wangyiyun_accid($data['owner_id']);

                //是否在群
                $stay_group = GroupUser::where('group_id', $data['group_id'])
                    ->where('user_id', $data['owner_id'])
                    ->first();
                if (!$stay_group) {
                    //拉人入群
                    $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
                    $imTeam->add($group->im_chat_id, $owner_ac_cid, [$new_owner_id], 0, '邀请进群');
                    //插入群成员
                    $group_user_map = [];
                    $group_user_map['group_id'] = $data['group_id'];
                    $group_user_map['user_id'] = $data['owner_id'];
                    $group_user_map['type'] = GroupUser::TYPE_NORMAL;
                    GroupUser::create($group_user_map);
                }

                //更改群主
                $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
                $imTeam->changeOwner($group->im_chat_id, $old_owner_ac_cid, $new_owner_id, 2);
                //将原先群主修改为普通成员
                GroupUser::where('group_id', $group->id)->where('user_id', $group->owner_id)->update(['type' => GroupUser::TYPE_NORMAL]);
                //将新人修改为群主
                GroupUser::where('group_id', $group->id)->where('user_id', $data['owner_id'])->update(['type' => GroupUser::TYPE_OWNER]);
            }

            $group->name = $data['name'];
            $group->chat_name = $data['name'];
            $group->avatar = $data['icon'];
            $group->announcement = $data['announcement'];
            $group->intro = $data['intro'];
            $group->order_id = $data['order_id'];
            $group->owner_id = $data['owner_id'];
            $group->save();

            DB::commit();
            return $this->success('ok', $group);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('createGroup:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 拉人进群
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addGroupUser(Request $request)
    {
        try {
            $is_service = $request->input('is_service');
            $user_ids = $request->input('user_ids');
            if (empty($user_ids))
                return $this->failure('请选择用户');

            $msg = $request->input('msg');

            $group_id = $request->input('group_id');
            if (empty($group_id))
                return $this->failure('请选择群组');

            $group_info = Group::where('id', $group_id)->first();
            if (empty($group_info)) {
                return $this->failure('群组不存在');
            }

            $check = GroupUser::where('group_id', $group_id)->whereIn('user_id', $user_ids)->first();
            if ($check) {
                return $this->failure('该用户已在群聊中');
            }

            $owner_ac_cid = make_wangyiyun_accid($group_info->owner_id);

            //生成群成员accid
            $new_user_ids = [];
            foreach ($user_ids as $user_id) {
                $new_user_ids[] = make_wangyiyun_accid($user_id);
            }
            //拉人入群
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->add($group_info->im_chat_id, $owner_ac_cid, $new_user_ids, 0, '邀请进群');

            //插入群成员
            $group_user_map = [];
            $group_user_map['group_id'] = $group_info->id;
            foreach ($user_ids as $val) {
                if ($is_service) {
                    $service_info = ServiceRoleUser::with('serviceUser')->where('user_id', $val)->orderByDesc('id')->first();
                    if ($service_info) {
                        $role = ServiceRole::where('id', $service_info->role_id)->first();
                    }
                }
                $group_user_map['user_id'] = $val;
                $group_user_map['role_id'] = $role->id ?? null;
                $group_user_map['role_name'] = $role->name ?? null;
                $group_user_map['nickname'] = $service_info->name ?? null;
                $group_user_map['type'] = GroupUser::TYPE_NORMAL;
                GroupUser::create($group_user_map);
            }
            return $this->success('ok', $user_ids);
        } catch (\Exception $e) {
            Log::error('addGroupUser:' . $e->getMessage());
            return $this->failure('line:' . $e->getLine() . '|msg:' . $e->getMessage());
        }
    }

    /**
     * 获取网易云群组列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getGroupList(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $no_page = $request->get('no_page');
            $group = Group::query()->with("order")
                ->when($keyword, function ($query) use ($keyword) {
                    $query->where(DB::raw('concat(name,im_chat_id)'), 'like', "%{$keyword}%");
                })
                ->whereNotNull('im_chat_id')
                //                ->where('type',Group::TYPE_WANGYIYUN)
                ->orderByDesc('id');

            if ($no_page) {
                $list = $group->get();
            } else {
                $list = $group->paginate();
            }
            //获取群主名称
            foreach ($list as $item) {
                //                $item->owner_name = WangYiYun::where('user_id',$item->owner_id)->value('name');
                $item->owner_name = User::where('id', $item->owner_id)->value('name');
                $item->user_count = GroupUser::where('group_id', $item->id)->count();
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            Log::error('getGroupList:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 获取群详细信息
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getGroupDetail(Request $request)
    {
        try {
            $group_id = $request->get('group_id');
            $group = Group::with('order')
                ->where('id', $group_id)
                //                ->where('type',Group::TYPE_WANGYIYUN)
                ->first();
            if (empty($group)) {
                return $this->failure('群不存在');
            }
            $group->owner_name = WangYiYun::where('user_id', $group->owner_id)->value('name');
            $group->user_count = GroupUser::where('group_id', $group->id)->count();
            return $this->success('ok', $group);
        } catch (\Exception $e) {
            Log::error('getGroupDetail:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }


    /**
     * 删除群聊
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function deleteGroup(Request $request)
    {
        DB::beginTransaction();
        try {
            $group_id = $request->get('group_id');
            $group = Group::where('id', $group_id)->first();
            if (empty($group)) {
                return $this->failure('群组不存在');
            }
            $owner_ac_cid = make_wangyiyun_accid($group->owner_id);
            //解散群
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->remove($group->im_chat_id, $owner_ac_cid);

            Group::where('id', $group_id)->delete();

            //删除群成员
            GroupUser::where('group_id', $group_id)->delete();

            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('deleteGroup:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 修改群昵称
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateGroupName(Request $request)
    {
        try {
            $group_id = $request->get('group_id');
            $group = Group::where('id', $group_id)->first();
            if (empty($group)) {
                return $this->failure('群组不存在');
            }
            $name = $request->get('name');
            $owner_ac_cid = make_wangyiyun_accid($group->owner_id);
            //修改群
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->updateTeamNick($group->im_chat_id, $owner_ac_cid, $owner_ac_cid, ['nick' => $name]);

            $group->name = $name;
            $group->chat_name = $name;
            $group->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('updateGroupName:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 修改群主id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function updateGroupOwner(Request $request)
    {
        DB::beginTransaction();
        try {
            $group_id = $request->get('group_id');
            $owner_id = $request->get('owner_id');
            $leave = $request->get('leave', 2);

            $group = Group::where('id', $group_id)->first();
            if (empty($group)) {
                return $this->failure('群组不存在');
            }
            $old_owner_ac_cid = make_wangyiyun_accid($group->owner_id);
            $new_owner_id = make_wangyiyun_accid($owner_id);
            //更改群主
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->changeOwner($group->im_chat_id, $old_owner_ac_cid, $new_owner_id, $leave);

            //将原先群主修改为普通成员
            GroupUser::where('group_id', $group->id)->where('user_id', $group->owner_id)->update(['type' => GroupUser::TYPE_NORMAL]);
            //将新人修改为群主
            GroupUser::where('group_id', $group->id)->where('user_id', $owner_id)->update(['type' => GroupUser::TYPE_OWNER]);

            //修改群拥有者
            $group->owner_id = $owner_id;
            $group->save();

            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('updateGroupOwner:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 获取某个群用户列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getGroupUserList(Request $request)
    {
        try {
            $group_id = $request->get('group_id');
            $keyword = $request->get('keyword');
            $no_page = $request->get('no_page');
            $query = GroupUser::query()->with('chatUser')->when($keyword, function ($query) use ($keyword) {
                $query->whereHas("chatUser", function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")->orWhere("mobile", "like", "%{$keyword}%");
                });
            })
                ->where('group_id', $group_id)
                ->orderByRaw(DB::raw('FIELD(ufutx_group_users.type, 1,2,0) asc, ufutx_group_users.id desc'));

            if ($no_page) {
                $list = $query->get();
            } else {
                $list = $query->paginate();
            }

            foreach ($list as $group) {
                if (!isset($group->chatUser)) {
                    continue;
                }
                $user = User::where('id', $group->chatUser->user_id)->first();
                $group->chatUser->name = !empty($group->chatUser->name) ? $group->chatUser->name : $user->name;
                $group->chatUser->icon = !empty($group->chatUser->icon) ? $group->chatUser->icon : $user->avatar;
                $group->chatUser->mobile = !empty($group->chatUser->mobile) ? $group->chatUser->mobile : $user->mobile;
                // $collaborator = Collaborator::where('user_id',$group->user_id)->first();
                // if(!empty($collaborator)){
                //     $group->chatUser->name = $collaborator->name;
                //     $group->chatUser->icon = $collaborator->avatar;
                //     $group->chatUser->mobile = $collaborator->mobile;
                // }
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            Log::error('getGroupUserList:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 踢出群聊
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function kickGroupUser(Request $request)
    {
        //        try {
        $group_id = $request->get('group_id');
        $group = Group::where('id', $group_id)->first();
        if (empty($group)) {
            return $this->failure('群组不存在');
        }
        $user_id = $request->get('user_id');
        if (empty($user_id)) {
            return $this->failure('请选择用户');
        }
        if ($user_id == $group->owner_id) {
            return $this->failure('群主暂时不支持踢出');
        }
        $owner_ac_cid = make_wangyiyun_accid($group->owner_id);
        $delete_user_ac_cid = make_wangyiyun_accid($user_id);
        $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
        try {
            $imTeam->kick($group->im_chat_id, $owner_ac_cid, $delete_user_ac_cid);
        } catch (\Exception $e) {
            Log::error('deleteGroupUser:' . $e->getMessage());
        }

        //删除群成员
        GroupUser::where('group_id', $group->id)->where('user_id', $user_id)->delete();
        return $this->success('ok');
        //        }catch (\Exception $e){
//            Log::error('deleteGroupUser:'.$e->getMessage());
//            return $this->failure($e->getMessage());
//        }
    }

    /**
     * 添加管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addManage(Request $request)
    {
        try {
            $group_id = $request->get('group_id');
            $group = Group::where('id', $group_id)->first();
            if (empty($group)) {
                return $this->failure('群组不存在');
            }

            $user_id = $request->get('user_id');
            if (empty($user_id)) {
                return $this->failure('请选择用户');
            }

            $group_user = GroupUser::where('group_id', $group_id)->where('user_id', $user_id)->first();
            if (!$group_user) {
                return $this->failure('所选用户不在群组');
            }

            $owner_ac_cid = make_wangyiyun_accid($group->owner_id);
            $add_user_ac_cid = make_wangyiyun_accid($user_id);
            //增加群管理员
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->addManager($group->im_chat_id, $owner_ac_cid, [$add_user_ac_cid]);

            //修改管理员
            $group_user->type = GroupUser::TYPE_MANAGE;
            $group_user->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('addManage:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 移除管理员
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function removeManage(Request $request)
    {
        try {
            $group_id = $request->get('group_id');
            $group = Group::where('id', $group_id)->first();
            if (empty($group)) {
                return $this->failure('群组不存在');
            }

            $user_id = $request->get('user_id');
            if (empty($user_id)) {
                return $this->failure('请选择用户');
            }

            $group_user = GroupUser::where('group_id', $group_id)->where('user_id', $user_id)->first();
            if (!$group_user) {
                return $this->failure('所选用户不在群组');
            }

            $owner_ac_cid = make_wangyiyun_accid($group->owner_id);
            $add_user_ac_cid = make_wangyiyun_accid($user_id);
            //增加群管理员
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->removeManager($group->im_chat_id, $owner_ac_cid, [$add_user_ac_cid]);
            //修改管理员
            $group_user->type = GroupUser::TYPE_NORMAL;
            $group_user->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('removeManage:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 修改群用户状态
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateGroupUserStatus(Request $request)
    {
        try {
            $group_id = $request->get('group_id');
            $group = Group::where('id', $group_id)->first();
            $status = $request->get('status');
            if (empty($group)) {
                return $this->failure('群组不存在');
            }

            $user_id = $request->get('user_id');
            if (empty($user_id)) {
                return $this->failure('请选择用户');
            }

            $group_user = GroupUser::where('group_id', $group_id)->where('user_id', $user_id)->first();
            if (!$group_user) {
                return $this->failure('所选用户不在群组');
            }

            $owner_ac_cid = make_wangyiyun_accid($group->owner_id);
            $user_ac_cid = make_wangyiyun_accid($user_id);
            //增加群管理员
            $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
            $imTeam->muteTlist($group->im_chat_id, $owner_ac_cid, $user_ac_cid, $status);
            //修改管理员
            $group_user->status = $status;
            $group_user->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('removeManage:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    /**
     * 获取群聊记录
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getGroupMessage(Request $request)
    {
        try {
            $group_id = $request->get('group_id');
            $keyword = $request->input('keyword');
            $group = Group::where('id', $group_id)->first();
            if (empty($group)) {
                return $this->failure('群组不存在');
            }
            $data = GroupMessage::with('user')
                ->whereHas('user', function ($query) use ($keyword) {
                    if ($keyword) {
                        $query->where('name', 'like', "%{$keyword}%");
                    }
                })
                ->where('group_id', $group_id)
                ->orderByDesc('id')
                ->paginate();
            return $this->success('ok', $data);
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }
    }

    public function updateGroup(Request $request)
    {
        $data = $request->only(['chat_qr_code']);
        $order_id = $request->input('order_id');
        $group = Group::where('order_id', $order_id)->first();
        if (empty($group)) {
            return $this->failure('请先绑定群聊');
        }
        Group::where('order_id', $order_id)->update($data);
        return $this->success('ok');
    }
}
