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

use Core\service\queue\QueueDispatcher;
use Core\service\BaseCoreService;
use Applications\sample\modules\order\repository\OrderRepository;

/**
 * Core Order Service
 * @package Applications\sample\modules\order\core
 */
class CoreOrderService extends BaseCoreService
{
    /**
     * 创建订单
     */
    public function create(int $uid, int $articleId, float $amount): array
    {
        $orderNo = date('YmdHis') . random_int(1000, 9999);
        $id = $this->repository()->createOrder($uid, $articleId, $orderNo, $amount);

        return [
            'code' => 0,
            'msg' => '下单成功',
            'data' => ['id' => $id, 'order_no' => $orderNo, 'amount' => $amount],
        ];
    }

    /**
     * 支付回调 → 标记已付 → 投递队列
     */
    public function markPaid(string $orderNo): array
    {
        $order = $this->repository()->findByOrderNo($orderNo);
        if (!$order) {
            return ['code' => 1, 'msg' => '订单不存在'];
        }
        if ((int)$order->status === 1) {
            return ['code' => 0, 'msg' => '订单已支付'];
        }

        $this->repository()->markPaid($orderNo);

        // 支付完成 → 投递通知队列
        try {
            $this->app->make(QueueDispatcher::class)->dispatch('sample.order.paid', [
                'order_id' => $order->id,
                'order_no' => $orderNo,
                'user_id' => $order->user_id,
                'article_id' => $order->article_id,
            ]);
        } catch (\Throwable $e) {
            // 队列不可用不影响主流程
        }

        return ['code' => 0, 'msg' => '支付成功'];
    }

    /**
     * 获取订单仓库实例
     * @return OrderRepository
     */
    private function repository(): OrderRepository
    {
        return $this->app->make(OrderRepository::class);
    }
}
