<?php

namespace App\Http\Controllers\V1;

use App\Models\Msg;
use App\Models\MsgRead;
use Illuminate\Http\Request;

class MsgController extends Controller
{

    public function __construct()
    {
        $this->user = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;

        //如果用户被删除，会自动退出登录
        if (!empty($this->user->deleted_at)) {
            $this->user->online = 0;
            $this->user->save();
            auth('api')->logout();
        }
    }

    /**
     * @return void
     * 消息列表
     */
    public function msgList(Request $request){

        $limit = $request->get('limit',10);

        $list = Msg::query()->with('user:id,name,avatar')->where('to_user_id',$this->userId)
            ->orWhere('to_user_id',0)
            ->orderByDesc("id")
            ->paginate($limit);

        foreach ($list as $v){
            if($v){
                $v['is_read'] = MsgRead::query()->where('user_id',$this->userId)->where('msg_id',$v['id'])->count();
            }
        }

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

    }

    /**
     * @param Request $request
     * @return void
     * 消息详情
     */
    public function msgDetail(Request $request){
        $id = $request->get('id');
        if(!$id){
            return $this->error("缺少参数ID!");
        }
        $msg = Msg::query()->with('user:id,name,avatar')->where('id',$id)->first();
        $MsgRead = MsgRead::query()->where('user_id',$this->userId)->where('msg_id',$msg['id'])->count();
        if(!$MsgRead){
            $data =[
                'user_id'=>$this->userId,
                'msg_id'=>$msg['id']
            ];
            MsgRead::query()->create($data); // 已读
        }
        return $this->success($msg);
    }

}
