<?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 InventoryImport implements ToArray, SkipsEmptyRows
{
    /**
     * @throws Exception
     */
    public function array(array $collection)
    {
        $header = $collection[0];
        unset($collection[0]);
        $externalSkuId = [];
        foreach ($collection as &$row) {
            $row = array_map(static function ($v) {
                return trim($v);
            }, $row);
            $externalSkuId[] = $row[0];
        }
        unset($row);
        $updateIds = $todayPrice = [];
        $day = DateTimeUtils::getToday();
        $dateTime = date('Y-m-d H:i:s');
        $hasGoodsSkus = GoodsSku::query()
            ->whereIn('external_sku_id', $externalSkuId)
            ->get(['id', 'status', 'external_sku_id'])
            ->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] + $row[3],
                    'cost' => $row[4],
                    'status' => 1,
                ]);
            } else {
                GoodsSku::query()->where('id', $goodsSku['id'])->update([
                    'stock' => $row[2] + $row[3],
                    'cost' => $row[4],
                ]);
            }
            $updateIds[] = $goodsSku['id'];
            DailyStockRecord::query()->where('sku_id', $goodsSku['id'])->where('day', $day)->update([
                'arrived_today_num' => $row[3],
                'inventory' => $row[2],
                'inventory_time' => $dateTime
            ]);
            $shopPrice = [];
            foreach ($row as $i => $v) {
                if ($i > 4) {
                    $shopPrice[$header[$i]] = $v;
                }
            }
            $todayPrice[] = [
                'day' => $day,
                'external_sku_id' => $goodsSku['external_sku_id'],
                'shop_price' => json_encode($shopPrice, 256)
            ];
        }
        if ($todayPrice) {
            TodayPrice::query()->delete();
            $model = new TodayPrice();
            $model->batchInsert($todayPrice);
        }
        sleep(2);
        $onSkuIds = GoodsSku::query()
            ->where('is_combination', 0)
            ->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));
    }
}
