<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Exceptions\WarningException;
use App\Filters\MaterialFilters;
use App\Http\Requests\Material\MaterialRequest;
use App\Material;
use Illuminate\Http\Request;

class MaterialController extends Controller
{
    // 耗材类型
    use AsyncResponse;
    public function index(Request $request,MaterialFilters  $filter)
    {
        $this->gate('耗材类型');
        $materials  = Material::query()->orderByDesc('id')->filter($filter)->paginate($request['paginate'] ?? 50);
        return view('maintenance/material/index',compact('materials'));
    }

    public function storeApi(MaterialRequest $request):array
    {
        $this->gate('耗材类型-编辑');
        $material = Material::query()->where('code',$request['code'])->first();
        if($material)return ['success' => false,'message'=>'code对应的耗材类型已存在'];
        try {
            $material = Material::query()->create($request->all(['code', 'name']));
            return ['success'=>true,'data'=>$material];
        } catch (\Exception $e) {
            return ['success' => false,'message' => $e->getMessage()];
        }
    }

    public function updateApi(MaterialRequest $request):array
    {
        $this->gate('耗材类型-编辑');
        /** @var Material $material */
        $material = Material::query()->find($request['id']);
        try {
            $material->update($request->all(['name', 'code']));
            return ['success' => true,'data'=>$material];
        } catch (WarningException $e) {
            return ['success'=>false,'message'=>$e->getMessage()];
        }
    }

    public function destroyApi($id):array
    {
        $this->gate('耗材类型-删除');
        /** @var Material $material */
        $material = Material::query()->find($id);
        try {
            $bool = $material->delete();
            if($bool>0)return ['success'=>true];
            else return ['success'=>false,'message'=>'删除失败'];
        } catch (WarningException $e) {
            return ['success'=>false,'message'=>$e->getMessage()];
        }
    }
}
