<?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 {
            // 数据库存储过程,7点定时执行
            $skus = GoodsSku::query()->get(['id', 'stock', 'two_days_ago_num', 'yesterday_num']);
            $data = [];
            $date = date('Y-m-d');
            foreach ($skus as $sku) {
                $data[] = [
                    'sku_id' => $sku->id,
                    'day' => $date,
                ];
                GoodsSku::where('id', $sku->id)->update([
                    'stock' => $sku->stock + $sku->two_days_ago_num + $sku->yesterday_num,
                    'yesterday_num' => $sku->stock,
                    'two_days_ago_num' => $sku->two_days_ago_num + $sku->yesterday_num,
                ]);
            }
            $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 = 1;
            $record = new DailyStockRecord();
            $record->batchInsert($data);
            $log->message = '成功';
            DB::commit();
        } catch (\Exception $exception) {
            $log->message = '失败' . $exception->getMessage();
            DB::rollBack();
        }
        $log->save();
        $this->info($log->message);
    }
}
