<?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();
        $hasGoodsIds = array_column($hasGoods, 'id');
        $hasGoods = ArrayUtils::index($hasGoods, 'goods_code');
        $updateIds = [];
        $day = DateTimeUtils::getToday();
        $dateTime = date('Y-m-d H:i:s');
        $hasGoodsSkus = GoodsSku::query()
            ->whereIn('goods_id', $hasGoodsIds)
            ->get(['id', 'status', 'stock', 'cost', 'sku_code', 'goods_id'])
            ->toArray();
        foreach ($collection as $row) {
            if (!isset($hasGoods[$row[0]])) {
                continue;
            }
            $goodsId = $hasGoods[$row[0]]['id'];
            $goodsSku = [];
            foreach ($hasGoodsSkus as $item) {
                if ($item['sku_code'] === $row[4] && $item['goods_id'] === $goodsId) {
                    $goodsSku = $item;
                    break;
                }
            }
            if (empty($goodsSku)) {
                Log::warning(json_encode($row, 256) . '=====库存导入未找到');
                continue;
            }
            if ('下架' === $goodsSku['status']) {
                GoodsSku::query()->where('id', $goodsSku['id'])->update([
                    'stock' => $row[6] + $row[7],
                    'cost' => $row[8],
                    'status' => 1,
                ]);
            } else {
                GoodsSku::query()->where('id', $goodsSku['id'])->update([
                    'stock' => $row[6] + $row[7],
                    'cost' => $row[8],
                ]);
            }
            $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
            ]);
        }
        sleep(2);
        $onSkuIds = GoodsSku::query()
            ->where('status', '>', 0)
            ->pluck('id')
            ->toArray();
        $downSkuIds = array_diff($onSkuIds, $updateIds);
        if ($downSkuIds) {
            $goodsSkus = GoodsSku::query()->whereIn('id', $downSkuIds)
                ->get(['id', 'yesterday_num', 'stock'])
                ->toArray();
            foreach ($goodsSkus as $goodsSku) {
                GoodsSku::query()->where('id', $goodsSku['id'])->update([
                    'yesterday_num' => $goodsSku['yesterday_num'] - $goodsSku['stock'],
                    'stock' => 0,
                ]);
            }
        }
        sleep(2);
        event(new StockUpdateEvent($onSkuIds, 1));
    }
}
