<?php

namespace App\Imports;

use App\Events\StockUpdateEvent;
use App\Models\CombinationGood;
use App\Models\GoodsSku;
use App\Models\GoodsSkuLocation;
use App\Utils\ArrayUtils;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithStartRow;

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

    public function array(array $array)
    {
        $main = [];
        foreach ($array as &$row) {
            $row = array_map(function ($value) {
                return trim($value);
            }, $row);
            if (empty($row[0]) || empty($row[1])) {
                continue;
            }
            // 组合商品
            if (empty($row[2]) && empty($row[3])) {
                $main[$row[1]] = [
                    'title' => $row[0],
                    'external_sku_id' => $row[1],
                    'item' => []
                ];
            } else {
                $main[$row[1]]['item'][] = [
                    'item_code' => $row[2],
                    'item_num' => $row[3],
                ];
            }
        }
        foreach ($main as $info) {
            if (empty($info['item'])) {
                continue;
            }
            DB::beginTransaction();
            try {
                $itemCodes = array_column($info['item'], 'item_code');
                $skus = GoodsSku::query()
                    ->whereIn('external_sku_id', $itemCodes)
                    ->get(['id', 'external_sku_id', 'stock'])
                    ->toArray();
                $skus = ArrayUtils::index($skus, 'external_sku_id');
                $stock = [];
                foreach ($info['item'] as $item) {
                    $stock[] = (int)($skus[$item['item_code']]['stock'] / $item['item_num']);
                }
                $stock = min($stock);
                $status = $stock ? (5 < $stock ? 1 : 2) : 0;
                $sku = GoodsSku::query()->updateOrCreate(
                    ['external_sku_id' => $info['external_sku_id'], 'is_combination' => 1],
                    ['title' => $info['title'], 'goods_id' => 0, 'sku_code' => $info['external_sku_id'], 'stock' => $stock, 'status' => $status]
                );
                CombinationGood::query()
                    ->where('goods_sku_id', $sku->id)
                    ->delete();
                foreach ($info['item'] as $item) {
                    CombinationGood::query()->create(['goods_sku_id' => $sku->id, 'item_id' => $skus[$item['item_code']]['id'], 'item_num' => $item['item_num']]);
                }
                DB::commit();
//                event(new StockUpdateEvent($sku, 0, true));
            } catch (\Exception $exception) {
                DB::rollBack();
            }
        }
    }
}
