<?php

namespace App\Models\Fpdx;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

/**
 * App\Models\Fpdx\RoomModel
 *
 * @property int $room_id
 * @property int $stage_id 期
 * @property string $room_name 房间名
 * @property array $member 成员
 * @property int $create_time 创建时间
 * @property int $type 1:分配对象;2:卖室友
 * @property string $attach
 * @property string $headimgurl 房间头像
 * @property int $open_at 开启时间
 * @property int $close_at 结束时间
 * @property int $keep 是否升级恋爱小屋
 * @property \Illuminate\Support\Carbon $created_at 创建时间
 * @property \Illuminate\Support\Carbon $updated_at 修改时间
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Fpdx\PairModel[] $pairs
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereAttach($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereCloseAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereCreateTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereHeadimgurl($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereKeep($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereMember($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereOpenAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereRoomId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereRoomName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereStageId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\RoomModel whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class RoomModel extends Model
{
    protected $table = 'fpdx_pair_rooms';

    public $dateFormat = 'U';

    protected $primaryKey = 'room_id';

    protected $fillable = [
        'room_id',
        'stage_id',
        'room_name',
        'member',
        'create_time',
        'type',
        'attach',
        'open_at',
        'close_at',
        'headimgurl'
    ];


    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function pairs()
    {
        return $this->hasMany(PairModel::class, 'room_id', 'room_id')->where('type', 1);
    }


    /**
     * 获取房间内的成员
     * @param $value
     * @return array
     */
    public function getMemberAttribute($value)
    {
        return explode(',', $value);
    }


    /**
     * 房间名称
     * @param $value
     * @return string
     */
    public function getRoomNameAttribute($value)
    {
        return $value ?: "第{$this->stage_id}期的房间";
    }

    /**
     * 获取某人某个类型的房间数量
     * @param  int  $type
     * @param  int  $uid
     * @return mixed
     */
    public function getCountByType(int $type, int $uid)
    {
        return $this->where('type', $type)->whereRaw("FIND_IN_SET(?, member)", [$uid])->count();
    }

    /**
     * 获取房间信息
     * @param $room_id
     * @param  int  $uid  序参考用户[0 => 匹配对象,..., 1 => uid ]
     * @return mixed
     * @throws \ApiException
     */
    public function getRoom($room_id, $uid = 0)
    {
        $room = $this->find($room_id);
        if (!collect($room)->isEmpty()) {
            $members = $room->member;
            $response = array();
            foreach ($members as $key => $value) {
                if ($value != $uid) {
                    array_push($response, $value);
                }
            }
            if (0 != $uid) {
                array_push($response, $uid);
            }
            $room->member = $response;
            return $room;
        } else {
            throw new \ApiException("未找到房间", 404);
        }
    }

    /**
     * 获取某人某期的房间信息
     * @param $stage_id
     * @param $uid
     * @return mixed
     * @throws \ApiException
     */
    public function getRoomByStage($stage_id, $uid)
    {
        $room = $this->where('stage_id', $stage_id)->where('type', 1)->whereRaw(
            'FIND_IN_SET(?, member)',
            [$uid]
        )->first();
        return $this->getRoom($room->room_id, $uid);
    }

    /**
     * 用户是否在某个房间里
     * @param  int  $room_id
     * @param  int  $uid
     * @return bool
     */
    public function isInRoom(int $room_id, int $uid)
    {
        $room = $this->where('room_id', $room_id)->whereRaw("FIND_IN_SET(?,member)", [$uid])->first();
        if (empty($room)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取某人的某期的房间信息
     * @param $stage_id
     * @param $uid
     * @return object
     * {
     *      "room_id": 房间id,
     *      "room_name": 房间名称,
     *      "stage_id": 期数,
     *      "uid": 用户id,
     *      "pair_uid": 匹配对象uid,
     *      "create_time": unix时间戳
     * }
     * @throws \ApiException
     */
    public function getRoomByStageUid($stage_id, $uid)
    {
        $room = $this->where('stage_id', $stage_id)->where('type', 1)->whereRaw(
            'FIND_IN_SET(?, member)',
            [$uid]
        )->first();
        if (empty($room)) {
            throw new \ApiException("未找到房间信息", 404);
        }
        $room = json_decode(json_encode($room[0]));
        $room->uid = $uid;
        $uids = explode(',', $room->member);
        array_map(function ($value) use (&$room) {
            if ($value != $room->uid) {
                $room->pair_uid = $value;
            }
        }, $uids);
        return $room;
    }


    /**
     * 通过期数获取房间列表
     * @param  int  $stage_id
     * @return \Illuminate\Support\Collection
     * @throws \ApiException
     * @deprecated
     */
    public function roomByStage(int $stage_id)
    {
        \DB::connection()->enableQueryLog();
        $rooms = $this->where('stage_id', '=', $stage_id)->get();
        foreach ($rooms as &$room) {
            $result = $this->getRoom($room->room_id);
            if (0 == $result['code']) {
                $room->member = $result['data']['member'];
            } else {
                $room->member = false;
            }
        }
        $rooms = $rooms->where('member', '!=', false);
        return $rooms;
    }

    /**
     * 通过成员获取卖室友房间
     * @param  int  $uid1
     * @param  int  $uid2
     * @return array|mixed
     */
    public function getRoomByMember(int $uid1, int $uid2)
    {

        $room = $this->where('type', 2)->where('member', "{$uid1},{$uid2}")->orWhere(
            'member',
            "{$uid2},{$uid1}"
        )->first();
        return $room;
    }

    /**
     * 加入房间
     * @param  int  $room_id
     * @param  string  $uid
     * @return bool
     * @throws \ApiException
     */
    public function joinRoom(int $room_id, string $uid)
    {
        $room = $this->find($room_id);
        if (collect($room)->isEMpty()) {
            throw new \ApiException("操作受到限制", 101);
        }
//        $members = explode(',', $room->member);
        $members = $room->member;
        array_push($members, $uid);
        $members = array_unique($members);
        $member = trim(implode(',', $members), ",");
        $room->member = $member;
        if ($room->save()) {
            Redis::zadd("session_room_{$uid}", time(), $room_id);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取房主信息by房间
     * @param  int  $room_id
     * @return MasterModel|Model|null|object
     * @throws \ApiException
     */
    public function getMaster(int $room_id)
    {
        $rm = RoomMasterModel::where([
            ['room_id', $room_id],
            ['type', 1]
        ])->first();
        if (collect($rm)->isEmpty()) {
            throw new \ApiException("未找到资源", 404);
        }
        $masterModel = new MasterModel();
        $master = $masterModel->getMaster($rm->uid);
        return $master;
    }

    /**
     * 获取管理员列表集合by房间
     * @param  int  $room_id
     * @return \Illuminate\Support\Collection
     */
    public function getAdministrator(int $room_id)
    {
        $rm = RoomMasterModel::where('room_id', $room_id)->get();
        $data = $rm->pluck('uid');
        return $data;
    }

    /**
     * 判断管理权限
     * @param  int  $room_id
     * @param  int  $uid
     * @return bool
     */
    public function isAdministrator(int $room_id, int $uid)
    {
        $rm = RoomMasterModel::where('room_id', $room_id)->get();
        $data = $rm->pluck('uid');
        if (in_array($uid, $data->toArray())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 增加房主cp数
     * @param  int  $room_id
     * @param  int  $increment
     * @return bool
     * @throws \ApiException
     */
    public function incrementCps(int $room_id, int $increment = 1)
    {
        $master = $this->getMaster($room_id);
        MasterModel::where('uid', $master->uid)->increment('cps', $increment);
        return true;
    }

    /**
     * 增加房主点赞数
     * @param  int  $room_id
     * @param  int  $increment
     * @return bool
     * @throws \ApiException
     */
    public function incrementThumbs(int $room_id, int $increment = 1)
    {
        $master = $this->getMaster($room_id);
        MasterModel::where('uid', $master->uid)->increment('thumbs', $increment);
        return true;
    }
}
