<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace Applications\sample\modules\article\listener;

use Core\service\queue\QueueDispatcher;
use Applications\sample\modules\article\event\ArticlePublished;
use Applications\sample\modules\article\repository\ArticleEventLogRepository;

/**
 * 文章发布事件监听器
 * Class ArticlePublishedListener
 * @package Applications\sample\modules\article\listener
 */
class ArticlePublishedListener
{
    /**
     * 处理文章发布事件
     * @param ArticlePublished $event
     * @return void
     */
    public function handle(ArticlePublished $event): void
    {
        $payload = [
            'article_id' => $event->articleId,
            'title' => $event->title,
            'trigger_time' => $event->triggerTime,
        ];

        $this->logs()->create([
            'article_id' => $event->articleId,
            'stage' => 'event',
            'event_code' => ArticlePublished::class,
            'message' => '文章发布事件已触发',
            'payload' => $payload,
            'status' => 1,
        ]);

        try {
            $result = $this->queue()->dispatch('sample.article.published', $payload, [
                'biz_key' => 'sample.article.published:' . $event->articleId,
            ]);

            $this->logs()->create([
                'article_id' => $event->articleId,
                'stage' => 'queue_dispatch',
                'event_code' => ArticlePublished::class,
                'topic' => 'sample.article.published',
                'message' => '已通过框架队列分发文章发布后续任务',
                'payload' => array_merge($payload, ['dispatch_result' => $result]),
                'status' => 1,
            ]);
        } catch (\Throwable $e) {
            $this->logs()->create([
                'article_id' => $event->articleId,
                'stage' => 'queue_dispatch',
                'event_code' => ArticlePublished::class,
                'topic' => 'sample.article.published',
                'message' => '队列分发失败：' . $e->getMessage(),
                'payload' => $payload,
                'status' => 0,
            ]);
        }
    }

    /**
     * 获取队列分发服务
     * @return QueueDispatcher
     */
    private function queue(): QueueDispatcher
    {
        return app()->make(QueueDispatcher::class);
    }

    /**
     * 获取日志仓储
     * @return ArticleEventLogRepository
     */
    private function logs(): ArticleEventLogRepository
    {
        return app()->make(ArticleEventLogRepository::class);
    }
}
