<?php

namespace App\Imports;

use App\Models\DailyStockRecord;
use App\Models\Goods;
use App\Models\GoodsSku;
use App\Utils\DateTimeUtils;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Utils\ArrayUtils;
use App\Events\StockUpdateEvent;

class InventoryImport implements ToCollection, SkipsEmptyRows
{
    /**
     * @throws Exception
     */
    public function collection(Collection $collection)
    {
        unset($collection[0]);
        $collection = $collection->toArray();
        $goodsCodes = [];
        foreach ($collection as &$row) {
            $row = array_map(static function ($v) {
                return trim($v);
            }, $row);
            $goodsCodes[] = $row[0];
        }
        unset($row);
        $hasGoods = Goods::query()->whereIn('goods_code', $goodsCodes)->get(['id', 'goods_code'])->toArray();
        $hasGoods = ArrayUtils::index($hasGoods, 'goods_code');
        $updateIds = [];
        $day = DateTimeUtils::getToday();
        $dateTime = date('Y-m-d H:i:s');
        foreach ($collection as $row) {
            if (!isset($hasGoods[$row[0]])) {
                continue;
            }
            $goodsSku = GoodsSku::query()
                ->where('goods_id', $hasGoods[$row[0]]['id'])
                ->where('sku_code', $row[4])
                ->first();
            if (empty($goodsSku)) {
                Log::warning(json_encode($row, 256) . '=====库存导入未找到');
                continue;
            }
            $goodsSku->stock = $row[6] + $row[7];
            if ('下架' === $goodsSku->status) {
                $goodsSku->status = 1;
            }
            $goodsSku->cost = $row[8];
            $goodsSku->save();
            event(new StockUpdateEvent($goodsSku));
            $updateIds[] = $goodsSku->id;
            DailyStockRecord::query()->where('sku_id', $goodsSku->id)->where('day', $day)->update([
                'arrived_today_num' => $row[7],
                'inventory' => $row[6],
                'inventory_time' => $dateTime
            ]);
        }
        $onSkuIds = GoodsSku::query()
            ->where('status', '<>', 0)
            ->pluck('id')
            ->toArray();
        $downSkuIds = array_diff($onSkuIds, $updateIds);
        foreach ($downSkuIds as $downSkuId) {
            $goodsSku = GoodsSku::query()->find($downSkuId);
            $goodsSku->yesterday_num -= $goodsSku->stock;
            $goodsSku->stock = 0;
            $goodsSku->save();
            event(new StockUpdateEvent($goodsSku));
        }
    }
}
