<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Model\OrderInquiry;
use App\Model\OrderInquiryCoupon;
use App\Model\OrderPrescription;
use App\Model\OrderPrescriptionProduct;
use App\Model\OrderProduct;
use App\Model\OrderProductItem;
use App\Model\Product;
use App\Model\ProductPlatformAmount;
use App\Model\UserCoupon;
use App\Services\InquiryService;
use App\Services\OrderProductService;
use App\Utils\Log;
use Hyperf\Amqp\Message\ConsumerDelayedMessageTrait;
use Hyperf\Amqp\Message\ProducerDelayedMessageTrait;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\DbConnection\Db;
use Hyperf\Snowflake\IdGeneratorInterface;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Message\Type;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 取消未支付药品/问诊订单
 * 延迟队列
 */
#[Consumer(nums: 1)]
class CancelUnpayOrdersDelayDirectConsumer extends ConsumerMessage
{
    use ProducerDelayedMessageTrait;
    use ConsumerDelayedMessageTrait;

    protected string $exchange = 'amqp.delay.direct';

    protected ?string $queue = 'cancel.unpay.orders.delay.queue';

    protected string $type = Type::DIRECT; //Type::FANOUT;

    protected string|array $routingKey = 'CancelUnpayOrders';

    public function consumeMessage($data, AMQPMessage $message): string
    {
        Log::getInstance()->error("开始执行 取消未支付订单 队列：" . json_encode($data, JSON_UNESCAPED_UNICODE));

        Db::beginTransaction();

        try {
            if ($data['order_type'] == 1) {
                // 问诊订单取消
                $InquiryService = new InquiryService();
                $result = $InquiryService->cancelUnpayInquiryOrder($data['order_no'], 5, "支付超时");

            } elseif ($data['order_type'] == 2) {
                // 药品订单取消
                $OrderProductService = new OrderProductService();
                $result = $OrderProductService->cancelUnpayProductOrder($data['order_no'], 3, "支付超时");
                
            } else {
                Log::getInstance()->error("取消未支付订单失败：order_type类型错误");
                return Result::DROP;// 销毁
            }

            if ($result['status'] == 0) {
                Db::rollBack();
                Log::getInstance()->error("取消未支付订单失败：" . $result['message']);
                return Result::DROP;// 销毁
            } elseif ($result['status'] == 2) {
                Db::rollBack();
                Log::getInstance()->info("取消未支付订单成功：" . $result['message']);
                return Result::ACK;// 销毁
            }

            Db::commit();
            Log::getInstance()->info("取消未支付订单 队列执行成功");
            return Result::ACK;
        } catch (\Exception $e) {
            Db::rollBack();
            Log::getInstance()->error("取消未支付订单执行失败：" . $e->getMessage());
            return Result::ACK; // 重回队列
        }
    }


}
