<?php

namespace App\Jobs;

use App\Models\Log;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use XuanChen\Coupon\Action\pingan\Verification;

class CheckCouponLog implements ShouldQueue
{

    use Dispatchable, InteractsWithQueue;

    public $queue = 'LISTENER';

    public $delay = 0;

    public $tries = 1;

    public $timeout = 30;

    protected $table;

    public function __construct(string $table)
    {
        $this->table = $table;
    }

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

        $count = (new Log())->setTable($this->table)
            ->whereNull('coupon_no')
            ->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)
                ->whereNull('coupon_no')
                ->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) {
                        $data = (new Verification())->decrypt($log->in_source['json']['data']);
                        $data = json_decode($data, true);
                        $log->update([
                            'coupon_no' => $data['couponNo']
                        ]);
                    }
                });

        }

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

    }

}