<?php

namespace App\Http\Controllers\Supplier;

use App\Events\BatchStockUpdateEvent;
use App\Http\Controllers\Controller;
use App\Http\Enum\ExcelKeyEnum;
use App\Imports\InventoryImport;
use App\Imports\LossImport;
use App\Models\DailyStockRecord;
use App\Models\GoodsSku;
use App\Models\Log as LogModel;
use App\Services\GoodSku\GoodSkuService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class DailyStockRecordController extends Controller
{
    public function __construct(Request $request)
    {
        $this->log = new LogModel([
            'module' => 'supplier',
            'action' => $request->getMethod(),
            'target_type' => 'dailyStockRecord',
        ]);
    }

    public function index(Request $request)
    {
        $build = DailyStockRecord::query()->whereNotNull("inventory_time")->filter()->with("goodsSku:id,name,title,external_sku_id");
        if (!empty($request->title)) {
            $build->whereHas('goodsSku', function ($query) use ($request) {
                $query->where('name', 'like', '%' . $request->title . '%');
            });
        }
        if (!empty($request->get('external_sku_id'))) {
            $build->whereHas('goodsSku', function ($query) use ($request) {
                $query->where('external_sku_id', '=', $request->external_sku_id);
            });
        }
        $start = $request->get("start_time");
        $end = $request->get("end_time");
        $dailyStockRecord = $build->when($start, function ($query) use ($start) {
            $query->where("created_at", ">=", $start);
        })->when($end, function ($query) use ($end) {
            $query->where("created_at", "<=", $end);
        })->orderByDesc("id")->paginate($request->get('per_page'));
        return JsonResource::collection($dailyStockRecord);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'external_sku_id' => 'required|string',
            'inventory' => 'required|integer',
        ]);
        if ($validator->fails()) {
            //校验失败返回异常
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());
            return response($this->res, $this->res['httpCode']);
        }
        $goodsSku = GoodsSku::query()->with("combinationGoods")->where('external_sku_id', "=", $request->external_sku_id)->first();
        if (empty($goodsSku)) {
            $this->res = [
                'httpCode' => 400,
                'message' => '查询不到sku信息',
                'errorCode' => "ERP001",
                'errorMessage' => '查询不到sku信息',
            ];
            return response($this->res, $this->res['httpCode']);
        }
        $goodsSkuWithInventory = array_merge($goodsSku->toArray(), ["inventory" => $request->inventory]);
        //同批量逻辑操作
        $goodSkuService = new GoodSkuService();
        $goodSkuService->inventory([$goodsSkuWithInventory]);
        return response($this->res, $this->res['httpCode']);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function inventoryBatchStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inventoryOrders' => 'required|array',
            'inventoryOrders.*.external_sku_id' => 'required|string',
            'inventoryOrders.*.inventory' => 'required|integer',
        ]);
        if ($validator->fails()) {
            //校验失败返回异常
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());
            return response($this->res, $this->res['httpCode']);
        }
        $inventoryKeyByExternalSkuIdMap = collect($request->inventoryOrders)->pluck(null, "external_sku_id")->toArray();
        $goodsSkus = GoodsSku::query()->with("combinationGoods")->whereIn('external_sku_id', array_keys($inventoryKeyByExternalSkuIdMap))
            ->get()->toArray();
        $goodsSkus = collect($goodsSkus)->map(function ($v) use ($inventoryKeyByExternalSkuIdMap) {
            if (!empty($inventoryKeyByExternalSkuIdMap[$v['external_sku_id']])) {
                $v['inventory'] = $inventoryKeyByExternalSkuIdMap[$v['external_sku_id']]['inventory'];
                return $v;
            }
        })->toArray();
        Log::info("goodsSkus", $goodsSkus);
        $goodSkuService = new GoodSkuService();
        $goodSkuService->inventory($goodsSkus);
        return response($this->res, $this->res['httpCode']);
    }


    public function inventoryImport(Request $request)
    {
        if (!$request->hasFile('inventoryFile')) {
            $this->res = [
                'httpCode' => 404,
                'errorCode' => 404404,
                'errorMessage' => 'not found inventory file',
            ];
        }
        try {
            $import = new InventoryImport();
            $path = $request->file('inventoryFile');
            Excel::import($import, $path);
            $this->addLog(0, 'import', 'inventory');
        } catch (ValidationException $exception) {
            $this->setValidatorFailResponse($exception->validator->getMessageBag()->getMessages());
        }

        return response($this->res, $this->res['httpCode']);
    }


}
