<?php

namespace App\Imports;

use App\Models\DailyStockRecord;
use App\Models\GoodsSku;
use App\Models\TodayPrice;
use App\Utils\DateTimeUtils;
use Exception;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use App\Utils\ArrayUtils;
use App\Events\StockUpdateEvent;

class NewSetImport implements ToArray, SkipsEmptyRows
{
    /**
     * @throws Exception
     */
    public function array(array $collection)
    {
        unset($collection[0]);
        $externalSkuId = [];
        foreach ($collection as &$row) {
            $row = array_map(static function ($v) {
                return trim($v);
            }, $row);
            $externalSkuId[] = $row[0];
        }
        unset($row);
        $day = DateTimeUtils::getToday();
        $updateIds = [];
        $hasGoodsSkus = GoodsSku::query()
            ->whereIn('external_sku_id', $externalSkuId)
            ->get(['id', 'status', 'external_sku_id', 'stock'])
            ->toArray();
        $hasGoodsSkus = ArrayUtils::index($hasGoodsSkus, 'external_sku_id');
        foreach ($collection as $row) {
            if (!isset($hasGoodsSkus[$row[0]])) {
                continue;
            }
            $goodsSku = $hasGoodsSkus[$row[0]];
            if ('下架' === $goodsSku['status']) {
                GoodsSku::query()->where('id', $goodsSku['id'])->update([
                    'stock' => $row[2] + $goodsSku['stock'],
                    'status' => 1,
                ]);
            } else {
                GoodsSku::query()->where('id', $goodsSku['id'])->update([
                    'stock' => $row[2] + $goodsSku['stock'],
                ]);
            }
            $updateIds[] = $goodsSku['id'];
            // 今日到货
            $record = DailyStockRecord::query()->where('sku_id', $goodsSku['id'])->where('day', $day)->first(['id', 'arrived_today_num']);
            $record->arrived_today_num += $row[2];
            $record->save();
        }
        sleep(2);
        event(new StockUpdateEvent($updateIds, 1));
    }
}
