<?php

namespace app\queue\redis;

use app\common\logic\PayNotifyLogic;
use app\common\model\retail\Cashierclass;
use app\common\model\store_order\StoreOrder;
use app\common\model\user_recharge\UserRecharge;
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['order_id'],
        ];
        $res = $pay->wechat->query($order);
        if ($res['trade_state'] == 'SUCCESS' && $res['trade_state_desc'] == '支付成功') {
            if(isset($data['pay_type']) && $data['pay_type']=='recharge'){
                PayNotifyLogic::handle('recharge', $res['out_trade_no'], $res);
            }else{
                PayNotifyLogic::handle('wechat_common', $res['out_trade_no'], $res);
            }
        }else{
            throw new BusinessException('订单支付中', 200);
        }
    }
    // 消费失败时
    public function onConsumeFailure(\Throwable $exception, $package)
    {
        // 直接更改消息队列数据结构,将最大重试次数max_attempts字段设置为0,即不再重试。
        if($package['attempts'] == 12){
            $pay = new PayService();
            $data = [
                'order_id' => $package['data']['order_id'],
                'paid' => 0,
            ];
            if($package['data']['pay_type']=='recharge'){
                $order=UserRecharge::where($data)->find();
                if($order){
                    $res=UserRecharge::where($data)->update(['status'=>-1]);
                    if($res){
                        PushService::push('store_merchant_' . $order['store_id'], $order['store_id'], ['type'=>'INDUSTRYMEMBERS','msg'=>'支付超时,订单已被取消,请重新提交订单','data'=>['id'=>$data['id'],'paid'=>0]]);
                        PushService::push('wechat_mmp_' . $order['uid'], $order['uid'], ['type'=>'INDUSTRYMEMBERS','msg'=>'支付超时,订单已被取消,请重新提交订单','data'=>['id'=>$data['id'],'paid'=>0]]);
                    }
                }
            }else{

                $order=StoreOrder::where($data)->find();
                if($order){
                        PushService::push('store_merchant_' . $order['store_id'], $order['store_id'], ['type'=>'cash_register','msg'=>'支付超时,订单已被取消,请重新提交订单']);
                }
            }
            $pay->wechat->close(['out_trade_no'=>$order['order_id']]);


        }
        return $package;
    }
}