<?php

namespace App\Imports;

use App\Events\BatchStockUpdateEvent;
use App\Jobs\SyncCostToMiaoXuan;
use App\Models\DailyStockRecord;
use App\Models\GoodsSku;
use App\Models\LossRecords;
use App\Models\PurchaseRecords;
use App\Models\User;
use App\Services\DeveloperConfig\DeveloperConfigService;
use App\Services\GoodSku\GoodSkuService;
use App\Utils\DateTimeUtils;
use App\Utils\GeneratorUtils;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use App\Utils\ArrayUtils;

class LossImport implements ToArray, SkipsEmptyRows
{
    /**
     * @throws Exception
     */
    public function array(array $collection)
    {
        if (!empty($collection)) {
            unset($collection[0]);
            $externalSkuIds = [];
            $buyerNames = [];
            foreach ($collection as &$row) {
                $row = array_map(static function ($v) {
                    return trim($v);
                }, $row);
                $externalSkuIds[] = $row[0];
                $buyerNames[] = $row[4];
            }
            unset($row);
            $allUpdateIds = [];
            $hasGoodsSkus = GoodsSku::query()
                ->whereIn('external_sku_id', $externalSkuIds)
                ->get(['id', 'status', 'external_sku_id', 'stock', "sale_stock", "cost", "is_combination"])
                ->toArray();
            $hasGoodsSkus = ArrayUtils::index($hasGoodsSkus, 'external_sku_id');
            $buyerUserIdKeyByNameMap = User::query()->whereIn("name", $buyerNames)->get()
                ->pluck("id", "name")->toArray();
            $today = DateTimeUtils::getToday();
            $batchNumber = GeneratorUtils::generateBatchNumber("import");
            //excel字段排序 編碼 商品名稱 报损數量 成本价  采购人名称 报损现象 报损原因 报损日期
            foreach ($collection as $row) {
                if (!isset($hasGoodsSkus[$row[0]])) {
                    continue;
                }
                DB::beginTransaction();
                try {
                    //执行库存操作
                    $goodsSkuItem = $hasGoodsSkus[$row[0]];
                    //保存記錄
                    $lossRecords = new LossRecords();
                    $lossRecords->batch_number = $batchNumber;
                    $lossRecords->external_sku_id = $row[0];
                    $lossRecords->num = $row[2];
                    $lossRecords->cost = $row[3];
                    $lossRecords->buyer_user_id = $buyerUserIdKeyByNameMap[$row[4]] ?? 0;
                    $lossRecords->buyer_name = $row[4] ?? '';
                    $lossRecords->phenomenon = $row[5] ?? '';
                    $lossRecords->reason = $row[6] ?? '';
                    $lossRecords->date = $today;
                    if (!empty($row[7])) {
                        $lossRecords->date = DateTimeUtils::excelUploadDateToString($row[7], $today);
                    }
                    $lossRecords->save();

                    $updateIds = GoodSkuService::computeSkuStock($goodsSkuItem, ["num" => 0 - $row[2], 'cost' => $row[3]]);
                    DB::commit();
                    $allUpdateIds = array_merge($allUpdateIds, $updateIds);
                } catch (\Exception $exception) {
                    DB::rollBack();
                }
            }
            Log::info("报损导入内容:", $collection);
            // 批量更新
            event(new BatchStockUpdateEvent(collect($allUpdateIds)->unique()->toArray()));
        }


    }
}
