<?php

namespace App\Listeners;

use App\Events\ConponCallback;
use App\Models\ActivityCouponLog;
use GuzzleHttp\Client;
use Illuminate\Contracts\Queue\ShouldQueue;
use RuntimeException;

class ConponCallbackListener implements ShouldQueue
{

    public $queue = 'LISTENER';

    /**
     * Handle the event.
     * @param  \App\Events\ConponCallback  $event
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(ConponCallback $event)
    {
        $acticity_coupon = $event->acticity_coupon;

        $user = $acticity_coupon->outlet->parent;
        if ($user->callback) {
            $client = new Client();

            $response = $client->request('post', $user->callback, [
                'timeout' => 30,
                'query'   => [
                    'code'   => $acticity_coupon->code,
                    'status' => $acticity_coupon->status,
                ],
            ]);

            $data = [
                'code' => $acticity_coupon->code,
                'type' => $acticity_coupon->status == 2 ? 'Verification' : 'Destroy',
                'url'  => $user->callback,
            ];

            $error = false;

            if ($response->getStatusCode() == 200) {
                $body   = $response->getBody();
                $result = json_decode($body->getContents(), true);

                $data['status'] = $result['code'] ?? '';
                $data['source'] = $result;
                $data['remark'] = $result['message'] ?? '';

            } else {
                $data['status'] = 0;
                $data['source'] = '';
                $data['remark'] = '接口错误';
                $error          = true;
            }

            ActivityCouponLog::create($data);

            if ($error) {
                throw new RuntimeException($data['remark']);
            }
        }

    }

}
