<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\Goods\Listeners;

use Modules\Order\Events\OrderTake;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Modules\Order\Services\OrderService;
use Modules\Member\Services\ScoreService;

class GoodsBlance implements ShouldQueue{

	/**
	 * Handle the event.
	 */
	public function handle(OrderTake $event){
		$order = $event->order;
		$item = $event->item;

		$member = $order->member()->first();
		$goods = $item->goods()->first();
		$sku = $item->sku()->first();

		if ($item->status == 3){
			//更新库存
			if ($item->goods_sku_id){
				$sku->stock = $sku->stock - $item->num;
				$sku->save();
			}else{
				$goods->stock = $goods->stock - $item->num;
				$goods->save();
			}
			// 积分商品
			if ($goods->goods_type == 0){
				app(ScoreService::class)->createScore(store_id: $item->store_id, order_id: $item->id, member_id: $member->uid, amount: $goods->score, type: 'income', account_type: 'order', remark: '积分商品购买积分');

				// 更新会员等级
				if ($member->level_id < $goods->level_id){
					$member->level_id = $goods->level_id;
					$member->save();
				}
			}
		}
	}
}