<?php

namespace App\Jobs;

use App\Models\Log;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

class CheckCouponByLog implements ShouldQueue
{

    use Dispatchable, InteractsWithQueue;

    public $queue = 'LISTENER';

    public $delay = 0;

    public $tries = 1;

    public $timeout = 30;


    protected $table;

    public function __construct(string $table, int $delay = 0)
    {
        $this->table = $table;
        $this->delay = $delay;
    }

    public function handle()
    {
        info(__CLASS__.' 开始处理 '.$this->table);

        $count = (new Log())->setTable($this->table)
            ->whereHas('coupon', function ($q) {
                $q->whereNull('pa_order_id');
            })
            ->where('path',
                'http://api.pingan.com.cn/open/vassPartner/appsvr/property/api/new/partner/redemption')
            ->where('out_source->code', 200)
            ->count();

        if ($count > 0) {

            (new Log())->setTable($this->table)
                ->whereHas('coupon', function ($q) {
                    $q->whereNull('pa_order_id');
                })
                ->where('path',
                    'http://api.pingan.com.cn/open/vassPartner/appsvr/property/api/new/partner/redemption')
                ->where('out_source->code', 200)
                ->chunkById(1000, function ($logs) {
                    foreach ($logs as $log) {
                        $log->coupon->update([
                            'pa_order_id'     => $log->out_source['data']['orderId'],
                            'pa_sub_order_id' => $log->out_source['data']['subOrderId'],
                        ]);
                    }
                });
        }

        info(__CLASS__.' '.$this->table.' 成功处理 '.$count);

    }

}