<?php

namespace App\Imports;

use App\Events\BatchStockUpdateEvent;
use App\Models\GoodsSku;
use App\Services\GoodSku\GoodSkuService;
use Exception;
use App\Models\Log as LogModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;

class SaleStockImport 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);
                if ($row[2] < 0) {
                    throw new Exception("商品编码{$row[0]}在售库存数不能小于0");
                }
                $inventoryKeyByExternalSkuIdMap[$row[0]] = $row[2];
                $externalSkuIds[] = $row[0];
            }
            unset($row);
            //新版盘点excel字段 编码 在售库存值 商品名称
            $updateIds = [];
            DB::beginTransaction();
            try {
                $logs = [];
                foreach ($externalSkuIds as $externalSkuId) {
                    // 成本
                    $goodsSku = GoodsSku::query()->where('external_sku_id', $externalSkuId)->first(['id', 'cost', 'sale_stock']);
                    Log::info("SKU", [$goodsSku]);
                    if (empty($goodsSku)) {
                        continue;
                    }
                    $costLog = [
                        'module' => 'goods',
                        'action' => "SaleStockImport",
                        'target_type' => 'goods_sku',
                        'target_id' => $goodsSku['id'],
                        'user_id' => Auth::id() ?? 999
                    ];
                    $costLog['target_field'] = 'sale_stock';
                    $costLog['before_update'] = $goodsSku->sale_stock;
                    $goodsSku->sale_stock = $inventoryKeyByExternalSkuIdMap[$externalSkuId] ?? 0;
                    if (0 >= $goodsSku->sale_stock) {
                        $status = GoodsSku::$STATUS_DOWN;
                    } else {
                        $status = GoodsSku::$STATUS_ON_SALE;
                    }
                    $goodsSku->status = $status;
                    $goodsSku->save();
                    $costLog['after_update'] = $goodsSku->sale_stock;
                    $logs[] = $costLog;
                    $updateIds[] = $goodsSku['id'];
                }
                $log = new LogModel();
                $log->batchInsert($logs);
                DB::commit();

            } catch (\Exception $exception) {
                DB::rollBack();
                throw new Exception($exception->getMessage());
            }
            if (!empty($updateIds)) {
                event(new BatchStockUpdateEvent($updateIds));
            }
        }
    }
}
