<?php

namespace Modules\User\Listeners;

use App\Notifications\SystemOpenVip;
use Exception;
use Modules\User\Events\UserOrderPaid;
use Modules\User\Models\IdentityLog;
use Modules\User\Models\UserStockLog;

class UserOrderPaidListeners
{

    /**
     * Notes: description
     *
     * @Author: 玄尘
     * @Date  : 2020/12/9 14:00
     * @param  UserOrderPaid  $event
     * @throws Exception
     */
    public function handle(UserOrderPaid $event)
    {
        try {
            $order = $event->order->refresh();
            $type  = UserStockLog::TYPE_INIT;
            if ($order->user->hasIdentity($order->identity->id)) {
                $type = UserStockLog::TYPE_IN;
            }

            $channel = IdentityLog::CHANNEL_AUTO;
            if (isset($order->source['channel'])) {
                $channel = $order->source['channel'];
            }

            $order->user->joinIdentity($order->identity->id, $channel, [
                'serial' => $order->source['serial'] ?? ''
            ]);//开通身份

            $order->user->notify(new SystemOpenVip($order->user->identityMiddle()->first()));

            if ($order->stock > 0) {
                $order->user->addStock($order->identity->id, $type, $order->stock);//赠水
            }
        } catch (Exception $exception) {
            throw new Exception($exception->getMessage());
        }
    }

}
