<?php

namespace App\Listeners;

use App\Events\SendEmailEvent;
use App\MailEvent;
use App\Notifications\SendEmailNotification;
use Tightenco\Collect\Support\Collection;

/**
 * 邮件发送监听器
 * Class SendEmailListener
 * @package App\Listeners
 */
class SendEmailListener
{


    /**
     * SendEmailListener constructor.
     */
    public function __construct()
    {

    }


    /**
     * Handle the event.
     *
     * @param SendEmailEvent $event
     * @return void
     */
    public function handle(SendEmailEvent $event)
    {
        //根据SendEmailEvent->className 从数据库中查找，判断状态是否开启
        $emailEvent = MailEvent::query()
            ->where('event_name', SendEmailEvent::class)
            ->where('is_active', true)
            ->first();
        if ($emailEvent) {
            /** @var MailEvent $emailEvent */
            $users = $this->getUsers($emailEvent);
            foreach ($users as $user) {//给这些用户发送通知
                $user->notify(new SendEmailNotification($emailEvent->template));//邮件模板由数据库中定制的模板为准
            }
        }
    }

    /**
     * 根據事件关联的角色，查询到用户
     * @param MailEvent $emailEvent
     * @return \Illuminate\Support\Collection|Collection
     */
    private function getUsers(MailEvent $emailEvent)
    {
        $users = collect();
        foreach ($emailEvent->roles as $role) {
            $users = $users->merge($role->users);
        }
        return $users;
    }
}
