<?php

namespace App\Imports;

use App\Models\GoodsSku;
use App\Services\GoodSku\GoodSkuService;
use Exception;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;

class InventoryImport implements ToArray, SkipsEmptyRows
{
    /**
     * @throws Exception
     */
    public function array(array $collection)
    {
        if (!empty($collection)) {
            unset($collection[0]);
            $externalSkuIds = [];
            $inventoryKeyByExternalSkuIdMap = [];
            foreach ($collection as &$row) {
                $row = array_map(static function ($v) {
                    return trim($v);
                }, $row);
                $inventoryKeyByExternalSkuIdMap[$row[0]] = $row[2];
                $externalSkuIds[] = $row[0];
            }
            unset($row);
            //新版盘点excel字段 编码 商品名称 盘点数
            $goodsSkus = GoodsSku::query()->with("combinationGoods")->whereIn('external_sku_id', $externalSkuIds)
                ->get()->toArray();
            $goodsSkus = collect($goodsSkus)->map(function ($v) use ($inventoryKeyByExternalSkuIdMap) {
                if (isset($inventoryKeyByExternalSkuIdMap[$v['external_sku_id']])) {
                    $v['inventory'] = $inventoryKeyByExternalSkuIdMap[$v['external_sku_id']];
                    return $v;
                }
            })->toArray();
            Log::info("goodsSkus",$goodsSkus);
            $goodSkuService = new GoodSkuService();
            $goodSkuService->inventory($goodsSkus);
        }
    }
}
