<?php

namespace App\Listeners;

use App\Events\ImSendMsg;
use App\Models\Friends\FriendContact;
use App\Models\User\UserModel;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;

/**
 * 更新联系人列表缓存
 * Class UpdateContactListCache
 * @package App\Listeners
 */
class UpdateContactListCache implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param  ImSendMsg  $event
     * @return void
     */
    public function handle(ImSendMsg $event)
    {
        $sendUser = UserModel::where('im_account', $event->senderIMAccount)->first();
        $receiveUser = UserModel::where('im_account', $event->receiverIMAccount)->first();
        if ($sendUser && $receiveUser) {
            FriendContact::updateOrCreate([
                'uid' => $sendUser->uid,
                'friend_uid' => $receiveUser->uid
            ], [
                'list_unread_msg_cnt' => DB::raw("`list_unread_msg_cnt` + 1"),
                'last_at' => $event->timestamp,
                'last_msg' => $event->contentArray
            ]);
            FriendContact::updateOrCreate([
                'uid' => $receiveUser->uid,
                'friend_uid' => $sendUser->uid
            ], [
                'list_unread_msg_cnt' => DB::raw("`list_unread_msg_cnt` + 1"),
                'last_at' => $event->timestamp,
                'last_msg' => $event->contentArray
            ]);
        }
    }
}
