<?php

namespace App\Imports;

use App\Models\GoodsSku;
use App\Models\GoodsSkuLocation;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithStartRow;

class GoodsSkuLocationImport implements ToArray, SkipsEmptyRows, WithStartRow
{
    public function startRow(): int
    {
        return 2;
    }

    public function array(array $array)
    {
        $externalSkuIds = $deleteLocation = [];
        foreach ($array as &$row) {
            $row = array_map(function ($value) {
                return trim($value);
            }, $row);
            $externalSkuIds[] = $row[2];
            $deleteLocation[] = $row[3];
        }
        GoodsSkuLocation::query()->whereIn('location', $deleteLocation)->delete();
        unset($row);
        $skus = GoodsSku::query()
            ->with('goods:id,title')
            ->whereIn('external_sku_id', $externalSkuIds)
            ->get(['id', 'goods_id', 'title', 'external_sku_id']);
        $goodsSkus = [];
        foreach ($skus as $sku) {
            $goodsSkus[$sku['external_sku_id']] = [
                'goods_id' => $sku['goods_id'],
                'goods_sku_id' => $sku['id'],
                'external_sku_id' => $sku['external_sku_id'],
                'goods_name' => $sku['goods']['title'] . $sku['title'],
            ];
        }
        $data = [];
        foreach ($array as $row) {
            if (isset($goodsSkus[$row[2]])) {
                $data[] = array_merge($goodsSkus[$row[2]], [
                    'date' => date('Y-m-d'),
                    'today_init_num' => $row[1],
                    'location' => $row[3],
                ]);
            }
        }
        $model = new GoodsSkuLocation();
        $model->batchInsert($data);
    }
}
