<?php

namespace App\Imports;

use App\Events\BatchStockUpdateEvent;
use App\Http\Enum\Purchase\PurchaseConfigEnum;
use App\Http\Enum\TargetTypeEnum;
use App\Jobs\SyncCostToMiaoXuan;
use App\Models\DailyStockRecord;
use App\Models\GoodsSku;
use App\Models\PurchaseRecords;
use App\Models\Suppliers;
use App\Models\User;
use App\Services\DeveloperConfig\DeveloperConfigService;
use App\Services\GoodSku\GoodSkuService;
use App\Utils\DateTimeUtils;
use App\Utils\GeneratorUtils;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use App\Utils\ArrayUtils;

class PurchaseImport implements ToArray, SkipsEmptyRows
{
    /**
     * @throws Exception
     */
    public function array(array $collection)
    {
        if (!empty($collection)) {
            unset($collection[0]);
            $externalSkuIds = [];
            $supplierNames = [];
            $buyerNames = [];
            foreach ($collection as &$row) {
                $row = array_map(static function ($v) {
                    return trim($v);
                }, $row);
                $externalSkuIds[] = $row[0];
                $buyerNames[] = $row[4];
                $supplierNames[] = $row[5];
            }
            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');
            //获取供货商
            $supplierIdKeyByNameMap = Suppliers::query()->whereIn("supplier_name", $supplierNames)->get()
                ->pluck("id", "supplier_name")->toArray();
            $buyerUserIdKeyByNameMap = User::query()->whereIn("name", $buyerNames)->get()
                ->pluck("id", "name")->toArray();
            $expireDay = DeveloperConfigService::getDefaultExpireDay();
            $today = DateTimeUtils::getToday();
            $batch_number = GeneratorUtils::generateBatchNumber("import");
            //excel字段排序 編碼 商品名稱 导购數量 成本价 采购人名称 供应商名称 采购日期
            foreach ($collection as $row) {
                if (!isset($hasGoodsSkus[$row[0]])) {
                    continue;
                }
                //执行库存操作
                $goodsSkuItem = $hasGoodsSkus[$row[0]];
                //保存記錄
                $purchaseRecords = new PurchaseRecords();
                $purchaseRecords->external_sku_id = $row[0];
                $purchaseRecords->batch_number = $batch_number;
                $purchaseRecords->num = $row[2];
                $purchaseRecords->cost = $row[3];
                $purchaseRecords->date = $today;
                if (!empty($row[6])) {
                    $purchaseRecords->date = DateTimeUtils::excelUploadDateToString($row[6], $today);
                }
                if (!empty($row[7])) {
                    $purchaseRecords->arrived_time = DateTimeUtils::excelUploadDateToString($row[7], $today,"Y-m-d H:i:s");
                }else{
                    $purchaseRecords->arrived_time = Carbon::now()->toDateTimeString();
                }
                $purchaseRecords->buyer_user_id = $buyerUserIdKeyByNameMap[$row[4]] ?? 0;
                $purchaseRecords->buyer_name = $row[4] ?? '';
                $purchaseRecords->supplier_name = $row[5] ?? '';
                $purchaseRecords->supplier_id = $supplierIdKeyByNameMap[$row[5]] ?? 0;
                $purchaseRecords->expire_time = Carbon::now()->addDays($expireDay)->toDateTimeString();
                $purchaseRecords->save();
                if (PurchaseConfigEnum::IS_AUTO_CHECK) {
                    $updateIds = GoodSkuService::computeSkuStock($goodsSkuItem, ["num" => $row[2], 'cost' => $row[3]], TargetTypeEnum::PURCHASE);
                    $allUpdateIds = array_merge($allUpdateIds, $updateIds);
                }
            }
            Log::info("采购导入内容:", $collection);
            if (PurchaseConfigEnum::IS_AUTO_CHECK) {
                // 批量更新
                event(new BatchStockUpdateEvent(collect($allUpdateIds)->unique()->toArray()));
            }
        }
    }
}
