<?php

namespace app\queue\redis;

use app\common\logic\PayNotifyLogic;
use app\common\model\retail\Cashierclass;
use app\common\service\pay\PayService;
use app\common\service\PushService;
use Webman\RedisQueue\Consumer;
use support\exception\BusinessException;

/**
 * 微信条码支付队列消费
 */
class CodePaySend implements Consumer
{
    // 要消费的队列名
    public $queue = 'send-code-pay';

    // 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        $pay = new PayService();
        $order = [
            'out_trade_no' => $data['number'],
        ];
        $res = $pay->wechat->query($order);
        if ($res['trade_state'] == 'SUCCESS' && $res['trade_state_desc'] == '支付成功') {
            PayNotifyLogic::handle('cashierclass', $res['out_trade_no'], $res);
        }else{
            throw new BusinessException('订单支付中', 200);
        }
    }
    // 消费失败时
    public function onConsumeFailure(\Throwable $exception, $package)
    {
        // 直接更改消息队列数据结构,将最大重试次数max_attempts字段设置为0,即不再重试。
        if($package['attempts'] ==$exception['max_attempts']){
            $data = [
                'number' => $package['data']['number'],
                'paid' => 0,
            ];
            $find=Cashierclass::where($data)->find();
            if($find){
                $order = Cashierclass::update($data);
                if($order){
                    PushService::push('cash_register_'.$package['data']['user_id'], $package['data']['user_id'], '支付超时,订单已被取消,请重新提交订单');
                }
            }
        }
        return $package;
    }
}