<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\DailyStockRecord;
use App\Models\GoodsSku;
use App\Models\Log;

class Inventory extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'timing:inventory';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时库存盘点';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::beginTransaction();
        try {
            $log = new Log();
            $log->module = 'goods';
            $log->action = 'PATCH';
            $log->target_type = 'goods_sku';
            $log->target_id = 0;
            $log->target_field = 'timingInventory';
            $log->user_id = 999;
            // 数据库存储过程,7点定时执行
            $data = [];
            $date = date('Y-m-d');
            GoodsSku::query()->chunk(500, static function ($skus) use (&$data, $date) {
                foreach ($skus as $sku) {
                    $data[] = [
                        'sku_id' => $sku->id,
                        'day' => $date,
                    ];
                    GoodsSku::query()->where('id', $sku->id)->update([
                        'yesterday_num' => $sku->stock,
                        'two_days_ago_num' => $sku->two_days_ago_num + $sku->yesterday_num,
                    ]);
                }
            });
            $record = new DailyStockRecord();
            $record->batchInsert($data);
            DB::commit();
            $log->message = '7点数据更新成功';
        } catch (\Exception $exception) {
            $log->message = '7点数据更新失败' . $exception->getMessage();
            DB::rollBack();
        }
        $log->save();
        $this->info($log->message);
    }
}
