<?php

namespace App\Http\Controllers\Goods;

use App\Http\Controllers\Controller;
use App\Http\Resources\GoodsTypeResource;
use App\Models\GoodsType;
use App\Models\Log as LogModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

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

    public function index(Request $request)
    {
        $goodsTypes = GoodsType::query()->paginate($request->get('per_page'));

        return GoodsTypeResource::collection($goodsTypes);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'names' => 'required|array',
            'names.*' => 'required|string|max:191|unique:goods_types,name',
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $goodsTypes = [];
        foreach ($request->names as $name) {
            $goodsTypes[] = ['name' => $name];
        }
        $goodsType = new GoodsType();
        if (!$goodsType->batchInsert($goodsTypes)) {
            $this->res = [
                'httpCode' => 500,
                'errorCode' => 500500,
                'errorMessage' => '批量添加失败',
            ];
        }
        $this->setAfterUpdate($goodsTypes);
        $this->addLog(0, 'add');

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

    public function show($id)
    {
        return new GoodsTypeResource(GoodsType::query()->find($id));
    }

    public function update($id, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'string',
                'max:191',
                Rule::unique('goods_types')->ignore($id),
            ]
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $goodsType = GoodsType::query()->find($id);
        $this->setBeforeUpdate($goodsType->name);
        $goodsType->name = request('name');
        $goodsType->save();
        $this->setAfterUpdate($goodsType->name);
        $this->addLog($id, 'name');

        return new GoodsTypeResource($goodsType);
    }

    public function destroy($id)
    {
        $goodsType = GoodsType::query()->find($id);
        $goodsType->delete();
        $this->addLog($id, 'status');

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