<?php

namespace App\Listeners;

use App\Events\BatchStockUpdateEvent;
use App\Events\BusinessOrdersUpdate;
use App\Http\Enum\CacheKeyEnum;
use App\Http\Enum\DevConfigKeyEnum;
use App\Http\Enum\Goods\SkuStatusEnum;
use App\Http\Service\MessageService;
use App\Models\BusinessGoodsSku;
use App\Models\DailyStockRecord;
use App\Models\DeveloperConfig;
use App\Models\GoodsSku;
use App\Models\Shop;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Services\Business\BusinessFactory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BusinessOrderUpdateListener implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param BusinessOrdersUpdate $event
     * @return void
     */
    public function handle(BusinessOrdersUpdate $event)
    {
        try {
            if (!empty($event->goodsSku)) {
                //查询库存是否满足告警规则
                //查找昨日统计的库存数据
                $record = DailyStockRecord::query()->where('sku_id', $event->goodsSku->id)->where("inventory", '>', 0)->orderByDesc('day')->first();
                Log::info("库存告警record", [$record]);
                $inventory = $record->inventory ?? 0;
                $expireTime = Carbon::now()->addMinutes(30)->toDateTimeString();
                $proportion = Cache::remember(CacheKeyEnum::STOCK_RULE_PROPORTION, $expireTime, function () {
                    $developerConfig = DeveloperConfig::query()->where("key", "=", DevConfigKeyEnum::STOCK_RULE_PROPORTION)->first();
                    return $developerConfig['value'] ?? DevConfigKeyEnum::DEFAULT_STOCK_RULE_PROPORTION;
                });
                //库存比例小于最近盘点多少告警 一天也只是告警一次
                if ($inventory > 10 && $inventory * $proportion > $event->goodsSku->stock) {
                    $messageService = new MessageService();
                    $messageService->createLowerStockNoticeMessage($inventory, $event->goodsSku->toArray());
                    //更新库存状态
                    GoodsSku::query()->where("id", "=", $event->goodsSku->id)->update([
                        "status" => SkuStatusEnum::NOTICE
                    ]);
                }
            }
        } catch (\Exception $exception) {
            Log::error("库存告警发生异常", ["error" => $exception->getMessage()]);
        }
    }
}
