<?php

namespace App\Http\Controllers\Goods;

use App\Http\Controllers\Controller;
use App\Http\Resources\GoodsSkuLocationResource;
use App\Imports\GoodsSkuLocationImport;
use App\Models\GoodsSkuLocation;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Facades\Excel;

class GoodsSkuLocationController extends Controller
{
    public function index(Request $request)
    {
        $goodsSkuLocation = GoodsSkuLocation::query()
            ->with([
                'goods:id,title,goods_code,brand_id,type_id',
                'goods.brand:id,name',
                'goods.type:id,name',
                'goodsSku:id,title,sku_code,stock',
            ])
            ->filter()
            ->paginate($request->get('per_page'));

        return GoodsSkuLocationResource::collection($goodsSkuLocation);
    }

    public function update(Request $request, $id)
    {
        $goodsSkuLocation = GoodsSkuLocation::query()->findOrFail($id);
        if ($location = $request->get('location')) {
            $goodsSkuLocation->location = $location;
        }
        if ($todayInitNum = $request->get('today_init_num')) {
            $goodsSkuLocation->today_init_num = $todayInitNum;
        }
        if ($status = $request->get('status')) {
            $goodsSkuLocation->status = $status;
        }
        if ($note = $request->get('note')) {
            $goodsSkuLocation->note = $note;
        }
        $goodsSkuLocation->save();

        return response()->json($this->res);
    }

    public function delete(Request $request, $id)
    {
        GoodsSkuLocation::query()->delete($id);

        return response()->json($this->res);
    }

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

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