<?php

namespace App\Http\Controllers\Fpdx;

use App\Exceptions\AlertException;
use App\Http\Resources\Fpdx\RoomResource;
use App\Models\PartnerModel;
use App\Models\User\Openid;
use App\Services\Pair\PairService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;
use App\Models\Fpdx\MessageModel;
use App\Models\User\UserModel;
use App\Models\Fpdx\RoomModel;
use App\Models\Fpdx\PairModel;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\RoomProfileModel;
use App\Models\Fpdx\GroupMemberModel;
use App\Models\Fpdx\GroupModel;
use App\Http\Controllers\Core\User;
use App\Http\Controllers\Core\Auth;
use App\Http\Controllers\Fpdx\Message as MessageObj;
use App\Http\Controllers\Wechat\Kfaccount;

class RoomController extends Controller
{
    /**
     * 创建房间
     * @param  int  $partner_id
     * @return array
     * @throws \ApiException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated
     */
    public function createRoom(int $partner_id)
    {
        $uid = Auth::auth();
        $partner = PartnerModel::find($partner_id);
        if (collect($partner)->isEmpty()) {
            return response([
                'code' => 101,
                'message' => '参数错误'
            ]);
        }
        $roomModel = new RoomModel();
        $room = $roomModel->getRoomByMember($uid, $partner->uid);
        if (empty($room)) {
            $room = $roomModel->fill([
                'stage_id' => -1,
                'member' => "{$uid},{$partner->uid}",
                'create_time' => time(),
                'type' => 2
            ]);
            if ($room->save()) {
                $roomModel->joinRoom($room->room_id, $uid);
                $roomModel->joinRoom($room->room_id, $partner->uid);
            } else {
                return response([
                    'code' => 505,
                    'message' => '数据库异常'
                ]);
            }
        }
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => [
                'room_id' => $room->room_id
            ],
        ]);
    }

    /**
     * 某人关于某房间的设置
     * @param  int  $room_id
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated
     */
    public function profile(int $room_id)
    {
        $uid = Auth::auth();
        $rpfModel = new RoomProfileModel();
        $profile = $rpfModel->profile($room_id, $uid);
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $profile
        ]);
    }

    /**
     * 更新房间设置
     * @param  Request  $request
     * @param  int  $room_id
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated
     */
    public function updateProfile(Request $request, int $room_id)
    {
        $uid = Auth::auth();
        $rpfModel = new RoomProfileModel();
        $rpfModel::updateOrCreate([
            'uid' => $uid,
            'room_id' => $room_id
        ], $request->toArray());
        return [
            'code' => 200,
            'message' => 'success'
        ];
    }


    /**
     * @param  Request  $request
     * @return array
     */
    public function updateAllowPhoto(Request $request)
    {
        $stage_id = $request->stage_id;
        $state = $request->state;
        $uid = Auth::auth();
        PairModel::where(['uid' => $uid, 'stage_id' => $stage_id])->update(['allow_photo' => $state]);
        return [
            'code' => 200,
            'message' => 'success'
        ];
    }

    /**
     * 清除聊天记录
     * @param  int  $room_id
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function clearMsg(Request $request, int $room_id)
    {
        $uid = Auth::auth();
        $ids = MessageModel::where([
            ['receive_uid', $room_id],
            ['msg_state', 1]
        ])->OrWhere([
            ['send_uid', $uid],
            ['receive_uid', $room_id]
        ])->orderBy('id', 'desc')->first(['id']);
        if (collect($ids)->isEmpty()) {
            $id = 0;
        } else {
            $id = $ids->id;
        }
        $rpfModel = new RoomProfileModel();
        $rpfModel::updateOrCreate([
            'uid' => $uid,
            'room_id' => $room_id
        ], ['last_clear_msg' => $id]);
        return [
            'code' => 200,
            'message' => 'success'
        ];
    }

    /**
     * 退房任务
     * @deprecated
     */
    public static function exitRoomTasking()
    {
        $datas = Redis::hgetall('fpdx_uid_rooms');
        foreach ($datas as $key => $value) {
            if (strpos($key, '_time') && time() > ($value + 144000)) {
                $uidTime = explode('_', $key);
                self::isExitRoom($uidTime[0]);
            }
        }
    }

    /**
     * goodby任务
     * @deprecated
     */
    public static function goodbyTasking()
    {
        $ings = ActivityModel::getActivitys();
        $roomModel = new RoomModel();
        $rooms = $roomModel->roomByStage($ings['ing']);
        foreach ($rooms as $room) {
            $response = self::initgoodby($room->member[0], $room->room_id);
            $messageObj = new MessageObj();
            if (0 == $response['code']) {
                $messageObj->pushKfMsg($response['data']['message_id']);
            }
            $response = self::initgoodby($room->member[1], $room->room_id);
            if (0 == $response['code']) {
                $messageObj->pushKfMsg($response['data']['message_id']);
            }
        }
    }

    /**
     * http进入房间
     * @param $room_id
     * @return array
     * @throws \ApiException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function intoRoom(Request $request, $room_id)
    {
        $uid = Auth::auth();
        return $this->into($uid, $room_id);
    }

    /**
     * cli进入房间
     * @param  int  $uid
     * @param  int  $room_id  房间号
     * @return array
     * @throws \ApiException
     */
    public static function into(int $uid, $room_id)
    {
        try {
            $old_room_id = self::get($uid);
            if ($room_id != $old_room_id) {
                $prefile_content = "切换连接, 连接创建";
                $roomModel = new RoomModel();
                $room = $roomModel->getRoom($old_room_id, $uid);
                $rpfModel = new RoomProfileModel();
                $profile = $rpfModel->profile($old_room_id, $room->member[0]);
                if ($profile->is_into_notive == 1) {
                    $notiveTime = Redis::hget("fpdx_exit_room_notives", "{$room->member[0]}_{$room_id}") ?: 0;
                }
            } else {
                $prefile_content = "连接创建";
            }
        } catch (\Exception $e) {
            $prefile_content = "连接创建";
        }
        Redis::hset("fpdx_uid_rooms", $uid, $room_id);
        Redis::hset("fpdx_uid_rooms", "{$uid}_time", time());
        if ($room_id == 'xxd') {
            // 小象导进房处理
        } else {
            $data = self::init($uid, $room_id);
            if ($data['room']->type == 2) {
                $photo_src = "http://oss.pocketuniversity.cn{$data['pair_user']->photo_src}";
            } else {
                if ($data['pair_user']->sex == 1) {
                    $photo_src = "http://oss.pocketuniversity.cn/media/2018-06-28/5b34d398f1a9c.jpg";
                } else {
                    $photo_src = " http://oss.pocketuniversity.cn/media/2018-06-28/5b34d396c2614.jpg";
                }
                if (!empty($data['pair_user']->photo_src) && $data['pair']->allow_photo == 1) {
                    $photo_src = "http://oss.pocketuniversity.cn{$data['pair_user']->photo_src}";
                }
            }
            $openid = Openid::ofPublic($uid)->value('openid');
            $news = array(
                [
                    'url' => "http://www.pocketuniversity.cn/ChargePartner/http/mediaCouple?page=userinfo&room_id={$room_id}",
                    'picurl' => $photo_src,
                    'title' => '创建连接成功，在当前对话框即可聊天！',
                    'description' => "对方昵称: {$data['pair_user']->nickname}\n对方星座: {$data['pair_user']->star}\n\n自我描述: {$data['pair_user']->introduce}\n交友期望: {$data['pair_user']->expect}\n\n点此查看CP资料"
                ]
            );
            Kfaccount::news($openid, $news, 'notice@admin');
            $array = [
                'touser' => $openid,
                'content' => $prefile_content . "成功，在当前界面直接发消息即可与CP通讯。当前聊天对象：{$data['pair_user']->nickname}（<a href='https://active.clewm.net/DnGCKt?qrurl=http%3A%2F%2Fqr23.cn'>查看活动攻略</a>）",
                'kf_account' => 'notice@admin'
            ];
            if (2 == $data['room']->type) {
                $array['content'] = "{$prefile_content}成功，在当前界面直接发消息即可与CP通讯。当前聊天对象：{$data['pair_user']->nickname}";
            }
            Kfaccount::text($array);
            if (2 != $data['room']->type) {
                self::welcome($uid, $room_id);
            }
            $rpfModel = new RoomProfileModel();
            $profile = $rpfModel->profile($room_id, $data['pair_user']->uid);
            if ($profile->is_into_notive == 1) {
                $notiveTime = Redis::hget("fpdx_into_exit_room_notives", "{$data['pair_user']->uid}_{$room_id}") ?: 0;
                if (2 != $data['room']->type && time() - $notiveTime > 86400 * 2) {
                    Redis::hset("fpdx_into_exit_room_notives", "{$data['pair_user']->uid}_{$room_id}", time());
                }
            }
            $msgObj = new MessageObj();
            $msgObj->pushHistoryMsg($room_id, $uid);
        }
        return [
            'code' => 200,
            'message' => 'success'
        ];
    }

    /**
     * 退出房间
     * @param $uid
     * @return array
     * @throws \ApiException
     */
    public static function exitRoom($uid)
    {
        $room_id = self::get($uid);
        Redis::hdel("fpdx_uid_rooms", $uid);
        Redis::hdel("fpdx_uid_rooms", "{$uid}_time");
        if ($room_id == 'xxd') {
            // 小象导退房处理
        } else {
            $openData = User::getOpenidByUid($uid);
            $array = [
                'touser' => $openData['openid'],
                'content' => "已退出聊天 （<a href='http://www.pocketuniversity.cn/ChargePartner/Http/mediaCouple?media_id=gh_b598cb7474d8'>查看消息列表</a>）",
                'kf_account' => 'notice@admin'
            ];
            Kfaccount::text($array);

            $roomModel = new RoomModel();
            $room = $roomModel->getRoom($room_id, $uid);
            $rpfModel = new RoomProfileModel();
            $profile = $rpfModel->profile($room_id, $room->member[0]);
            if ($profile->is_into_notive == 1) {
                $notiveTime = Redis::hget("fpdx_into_exit_room_notives", "{$room->member[0]}_{$room_id}") ?: 0;
                if (2 != $room->type && time() - $notiveTime > 86400 * 2) {
                    Redis::hset("fpdx_into_exit_room_notives", "{$room->member[0]}_{$room_id}", time());
                }
            }
        }

        return [
            'code' => 0,
            'msg' => '成功'
        ];
    }

    /**
     * 被动退房
     * @param $uid
     * @throws \ApiException
     * @deprecated
     */
    public static function isExitRoom($uid)
    {
        $room_id = self::get($uid);
        Redis::hdel("fpdx_uid_rooms", $uid);
        Redis::hdel("fpdx_uid_rooms", "{$uid}_time");
        if ($room_id == 'xxd') {
            // 小象导被动退房处理
        } else {
            $openid = Openid::ofPublic($uid)->value('openid');
            $array = [
                'touser' => $openid,
                'content' => "你已有40小时没有和你的CP聊天了哦,现已为你自动退房（房间号:{$room_id}）。对方将接收不到你的消息。向公众号回复「进房」重新进房吧！",
                'kf_account' => 'notice@admin'
            ];
            Kfaccount::text($array);
        }
    }

    /**
     * 获取当前房间
     * @param $uid
     * @return mixed
     * @throws \ApiException
     */
    public static function get($uid)
    {
        $room_id = Redis::hget("fpdx_uid_rooms", $uid);
        if ($room_id) {
            return $room_id;
        } else {
            throw new \ApiException('不在房间里', 1);
        }
    }

    /**
     * 加载欢迎数据
     * @param $uid
     * @param $room_id
     * @return array
     * @throws \ApiException
     */
    private static function init($uid, $room_id)
    {
        // 当前用户昵称
        $userModel = new UserModel();
        $user = $userModel->findOrFail($uid);
        // 期数，房间号,匹配对象uid
        $roomModel = new RoomModel();
        $room = $roomModel->getRoom($room_id, $uid);
        if (2 != $room->type) {
            // 获取报名公众号
            $pairModel = new PairModel();
            $pair = $pairModel->getPairByStageUid($room->stage_id, $uid);
        }
        // 匹配对象昵称/uid
        $pairUser = $userModel->findOrFail($room->member[0]);
        return [
            'user' => $user,
            'room' => $room,
            'pair' => $pair ?? null,
            'pair_user' => $pairUser
        ];
    }

    /**
     * 欢迎进入房间
     * @param $uid 用户id
     * @param $room_id 房间id
     * @return boolean
     * @throws \ApiException
     */
    public static function welcome($uid, $room_id)
    {
        $data = self::init($uid, $room_id);
        $tags = Tag::getTagByUid($data['pair_user']->uid);
        if (!isset($tags[1])) {
            $tags[1] = array();
        }
        if (!isset($tags[2])) {
            $tags[2] = array();
        }
        $welcome3_1 = '';
        $welcome3_2 = '';
        $sx = '';
        $kl = '';
        foreach ($tags[1] as $value) {
            if ($value['belong'] == 1) {
                $sx .= $value['name'] . ",";
            }
        }
        if (!empty($sx)) {
            $welcome3_1 = "我的属性是：" . rtrim($sx, ',') . "。";
        }
        foreach ($tags[2] as $value) {
            if ($value['belong'] == 1) {
                $kl .= $value['name'] . ",";
            }
        }
        if (!empty($kl)) {
            $welcome3_2 = "可以跟我聊聊：" . rtrim($kl, ',') . "。";
        }
        $welcome3 = "嗨~我是{$data['pair_user']->nickname},{$welcome3_1}{$welcome3_2}希望这三天能相处愉快~（机器人代发）";
        $msgModel = new MessageModel();
        $where = [
            ['send_uid', '=', $uid],
            ['receive_uid', '=', $room_id],
            ['msg_type', '=', -6]
        ];
        $welcome = $msgModel->where($where)->first();
        if (collect($welcome)->isEmpty()) {
            $content = [
                0 => [
                    'type' => 'text',
                    'content' => $welcome3,
                    'kf_account' => $data['pair_user']->kf_account,
                ],
            ];
            // 消息存档
            $add = array(
                'send_uid' => $uid,
                'receive_uid' => $room_id,
                'msg_content' => json_encode($content),
                'msg_type' => -6,
                'create_time' => time(),
            );
            $message_id = \DB::table('fpdx_pair_room_messages')->insertGetId($add);
            $msgObj = new MessageObj();
            $msgObj->pushKfMsg($message_id);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送活动结束语
     * @param $uid
     * @param $room_id 房间号
     * @return array
     * @throws \ApiException
     * @deprecated
     */
    public static function initgoodby($uid, $room_id)
    {
        // 期数，房间号,匹配对象uid
        $roomModel = new RoomModel();
        $room = $roomModel->getRoom($room_id, $uid);

        // 获取报名公众号
        $pairModel = new PairModel();
        $pair = $pairModel->getPairByStageUid($room['stage_id'], $uid);

        // 匹配对象昵称/uid
        $userModel = new UserModel();
        $pairUser = $userModel->findOrFail($room['member'][0]);

        // 发送goodby语
        $msgModel = new MessageModel();
        $where = [
            ['send_uid', '=', $uid],
            ['receive_uid', '=', $room_id],
            ['msg_type', '=', -10]
        ];

        $goodby = $msgModel->where($where)->first();
        if (collect($goodby)->isEmpty()) {
            $goodby3 = "有人说遇到相爱的人的概率只有0.0049%。但我们认为，两个人能不能相爱，这根本不是概率和命运的事情，而是你缺少踏出第一步的勇气，感谢你们的参与，并认真的对待这3天的时间。或是成为朋友，或是恋人，还是继续上路寻找那个对的人。如果这3天给了你不一样的恋爱体验，你愿意把这个活动分享给你周围的人吗？我们仍会继续制造相遇！";
            $content[2] = array(
                'type' => 'text',
                'content' => $goodby3
            );
            $add = array(
                'send_uid' => $uid,
                'receive_uid' => $room_id,
                'msg_content' => json_encode($content),
                'msg_type' => -10,
                'create_time' => time()
            );
            $message_id = \DB::table('fpdx_pair_room_messages')->insertGetId($add);
            return [
                'code' => 0,
                'data' => [
                    'message_id' => $message_id,
                    'pair_data' => $pairUser,
                    'pairt_media_id' => $pair['media_id'],
                ],
            ];
        } else {
            return [
                'code' => 1,
                'msg' => '已经发送过',
                'data' => [
                    'pair_data' => $pairUser,
                    'pairt_media_id' => $pair['media_id'],
                ],
            ];
        }
    }


    /**
     * 获取房间列表
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @throws \ApiException
     */
    public function sessionRoomList()
    {
        $uid = Auth::auth();

        $room_ids = Redis::zrange("session_room_{$uid}", 0, -1);
        if (empty($room_ids)) {
            $room_ids = array();
        }
        $hides = Redis::smembers("session_room_hide_{$uid}");
        if (empty($hides)) {
            $hides = array();
        }

        $userModel = new UserModel();
        $rooms = RoomModel::whereIn('room_id', $room_ids)->get();

        foreach ($rooms as &$room) {
            if (in_array($room->room_id, $hides)) {
                $room->hide = 1;
            } else {
                $room->hide = 0;
            }
            $room->msg_count = 0;

            $room->last_msg = json_decode(Redis::hget("session_msg_room_{$room->room_id}", 'last_msg'));
            $room_id = Redis::hget("fpdx_uid_rooms", $uid) ?? 0;
            if ($room_id && $room_id == $room->room_id) {
                $room['chatting'] = true;
            } else {
                $room['chatting'] = false;
            }
            if ($room->type != 3) {
                $uids = explode(',', $room->member) ?? [];
                foreach ($uids as $value) {
                    if ($uid != $value) {
                        $info = $userModel->findOrFail($value);
                        if ($room->type == 1) {
                            $info->pair = PairModel::select('allow_photo')->where([
                                'uid' => $info->uid,
                                'stage_id' => $room->stage_id
                            ])->first();
                            $info->pair->self_allow_photo = PairModel::where([
                                'uid' => $uid,
                                'stage_id' => $room->stage_id
                            ])->value('allow_photo');
                        }
                        $room->other = $info;
                        $isNew = MessageModel::where([
                            ['send_uid', $value],
                            ['receive_uid', $room->room_id],
                            ['msg_type', -1]
                        ])->first();
                        if (collect($isNew)->isEmpty()) {
                            $room->is_new = false;
                        } else {
                            $room->is_new = true;
                        }
                        $room_id = Redis::hget("fpdx_uid_rooms", $value);
                        if ($room_id && $room_id == $room->room_id) {
                            $room['online'] = true;
                        } else {
                            $room['online'] = false;
                        }
                    }
                }
            } else {
            }
            $room->last_msg = json_decode(Redis::hget("session_msg_room_{$room->room_id}", 'last_msg'));
        }
        return [
            'code' => 200,
            'message' => 'success',
            'data' => $rooms
        ];
    }

    /**
     * 用户删除(不常联系)房间列表
     * @param  int  $room_id
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function delRoomList(int $room_id)
    {
        $uid = Auth::auth();
        $hides = Redis::smembers("session_room_hide_{$uid}");
        if (empty($hides)) {
            $hides = array();
        }
        if (in_array($room_id, $hides)) {
            Redis::srem("session_room_hide_{$uid}", $room_id);
        } else {
            Redis::sadd("session_room_hide_{$uid}", $room_id);
        }
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 获取room聊天记录
     * @param $room_id
     * @param  Request  $request
     * @return mixed
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function roomMsgLogs($room_id, Request $request)
    {
        $firstRow = ($request->get('page') - 1) * 20;

        $uid = Auth::auth();

        $rpfModel = new RoomProfileModel();
        try {
            $res = $rpfModel->profile($room_id, $uid);
            $last_clear_msg = $res->last_clear_msg ?: 0;
        } catch (\Exception $e) {
            $last_clear_msg = 0;
        }
        $datas = MessageModel::where('id', '>', $last_clear_msg)
            ->where(function ($query) use ($room_id, $uid) {
                return $query->where([
                    ['send_uid', $room_id],
                    ['receive_uid', $uid]
                ])->orWhere('receive_uid', $room_id);
            })->WhereNull('deleted_at')->orderBy('id', 'desc')->skip($firstRow)->take(20)->get();
        foreach ($datas as &$data) {
            if (in_array($data->msg_type, [-1, -8])) {
                $data->user = UserModel::find($data->send_uid);
            }
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $datas
        );
    }

    /**
     * 获取最新聊天记录
     * @param  int  $room_id
     * @param  int  $last_msg
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function chatMsg(int $room_id, int $last_msg)
    {
        $uid = Auth::auth();
        // 清除最后推送
        Redis::hdel("fpdx_group_room_notives", "{$uid}_{$room_id}");
        $datas = MessageModel::where('id', '>', $last_msg)
            ->where(function ($query) use ($room_id, $uid) {
                return $query->where('receive_uid', $room_id);
            })->WhereNull('deleted_at')->get();
        foreach ($datas as &$data) {
            if (in_array($data->msg_type, [-1, -8])) {
                $data->user = UserModel::find($data->send_uid);
            }
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $datas
        );
    }

    /**
     * 确认自己落单
     * @param  Request  $request
     * @return array
     * @throws AlertException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated
     */
    public function alone(Request $request)
    {
        $stage_id = $request->stage_id;
        $activity_type = $request->input('activity_type', '72h');
        $uid = Auth::auth();
        $group_id = GroupMemberModel::where([
            'stage_id' => $stage_id,
            'uid' => $uid,
            'activity_type' => $activity_type,
            'type' => 'alone'
        ])->value('group_id');
        if (!$group_id) {
            $groups = GroupModel::where([
                'stage_id' => $stage_id,
                'type' => 'alone',
                'activity_type' => $activity_type
            ])->get();
            foreach ($groups as $group) {
                $number = GroupMemberModel::where([
                    'stage_id' => $stage_id,
                    'group_id' => $group->id,
                    'activity_type' => $activity_type,
                    'type' => 'alone'
                ])->count();
                if ($number < $group->number) {
                    $group_id = $group->id;
                    break;
                }
            }
            if (empty($group_id)) {
                throw new AlertException("落单群已经满", 401);
            }
            GroupMemberModel::create([
                'uid' => $uid,
                'stage_id' => $stage_id,
                'group_id' => $group_id,
                'activity_type' => $activity_type,
                'type' => 'alone'
            ]);
        }
        $group = GroupModel::find($group_id);
        return [
            'code' => 200,
            'message' => 'success',
            'data' => [
                'group' => $group,
            ]
        ];
    }

    /**
     * qq群列表
     * @param  Request  $request
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function groups(Request $request)
    {
        $uid = Auth::auth();
        $groups = GroupMemberModel::where('uid', $uid)
            ->when($request->filled('stage_id'), function ($query) use ($request) {
                return $query->where('stage_id', $request->stage_id);
            })->when($request->filled('activity_type'), function ($query) use ($request) {
                return $query->where('activity_type', $request->activity_type);
            })->get();
        foreach ($groups as $group) {
            $group->group = GroupModel::find($group->group_id);
        }
        return [
            'code' => 200,
            'message' => 'success',
            'data' => [
                'groups' => $groups,
            ]
        ];
    }

    /**
     * 获取忽略关键词
     * @return array
     */
    public function getHideKey()
    {
        $keys = Redis::smembers("fpdx_hide_msg_key");
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => array(
                'keys' => $keys
            ),
        );
    }

    /**
     * 删除忽略关键词
     * @param  string  $key
     * @return array
     */
    public function delHideKey(string $key)
    {
        Redis::srem("fpdx_hide_msg_key", $key);
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 添加忽略关键词
     * @param  string  $key
     * @return array
     */
    public function addHideKey(string $key)
    {
        Redis::sadd("fpdx_hide_msg_key", $key);
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }


    /**
     * 获取当前期房间
     * @return array
     */
    public function getCurrentRoom()
    {
        $uid = Auth::auth();
        try {
            $ings = ActivityModel::getActivitys();
            $roomObj = new RoomModel();
            $data = $roomObj->getRoomByStage($ings['ing'], $uid);
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => $data
            );
        } catch (\Exception $e) {
            return array(
                'code' => 201,
                'message' => '未获取编号',
            );
        }
    }


    /**
     * 保持CP关系的房间
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated
     */
    public function keepRoom(Request $request)
    {
        $uid = Auth::auth();
        $room_id = (new PairService())->keepRoom($uid);
        if (!$room_id) {
            return response([
                'code' => 200,
                'message' => 'OK',
                'data' => null
            ]);
        }
        $room = RoomModel::findOrFail($room_id);
        return new RoomResource($room);
    }


    /**
     * 保持关系
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws AlertException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated
     */
    public function keep(Request $request, $room_id)
    {
        $uid = Auth::auth();
        $pairService = new PairService();
        $pairService->keep($uid, $room_id);
        return response([
            "code" => 200,
            "message" => "Success"
        ]);
    }


    /**
     * 取消关系
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws AlertException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @deprecated
     */
    public function unKeep(Request $request, $room_id)
    {
        $uid = Auth::auth();
        try {
            $pairService = new PairService();
            $pairService->unKeep($uid, $room_id);
        } catch (\Exception $e) {
            throw new AlertException($e);
        }
        return response([
            "code" => 200,
            "message" => "Success"
        ]);
    }


    /*-------------------------------------------------*/
    public function index()
    {
        $uid = Auth::auth();
        $rooms = RoomModel::find(
            PairModel::where('uid', $uid)->pluck('room_id')
        );
        foreach ($rooms as $room) {
            $room->pair;
            $room->id = $room->room_id;
        }
        return response([
            'code' => 200,
            'data' => $rooms
        ]);
    }


    /**
     * 获取房间信息
     * @param  int  $room_id
     * @return array
     */
    public function show(int $room_id)
    {
        $uid = Auth::auth();
        $room = RoomModel::findOrFail($room_id);
        if (!in_array($uid, $room->member)) {
            return response([
                'code' => 403002,
                'message' => '非房间成员'
            ]);
        }
        return new RoomResource($room);
    }


    /**
     * 修改
     * @param  Request  $request
     * @param  int  $room_id
     * @return RoomResource|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function update(Request $request, int $room_id)
    {
        $uid = Auth::auth();
        $room = RoomModel::findOrFail($room_id);
        if (!in_array($uid, $room->member)) {
            return response([
                'code' => 403002,
                'message' => '非房间成员'
            ]);
        }
        $this->validate($request, [
            'room_name' => 'max:16',
        ]);
        $room->update($request->only('room_name', 'headimgurl'));
        return new RoomResource($room);
    }
}
