<?php

namespace App\Http\Controllers;

use App\CarType;
use App\Components\AsyncResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class CarTypesController extends Controller
{
    use AsyncResponse;
    public function index()
    {
        if(!Gate::allows('车型-查询')){ return redirect(url('/'));  }
        $carTypes=CarType::orderBy('id', 'DESC')->paginate(50);
        return view('maintenance.carType.index',['carTypes'=>$carTypes]);
    }

    public function create()
    {
        if(!Gate::allows('车型-录入')){ return redirect(url('/'));  }
        return view('maintenance.carType.create');
    }


    public function store(Request $request)
    {
        if(!Gate::allows('车型-录入')){ return redirect(url('/'));  }
        $id=false;
        $this->validatorCarType($request,$id)->validate();
        $carTypes=$request->input('CarType');
        if(CarType::create($carTypes)){
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/carType')->with('successTip','新车辆“'.$request->input('CarType.name').'”添加成功');
        };
    }

    public function edit($id)
    {
        if(!Gate::allows('车型-编辑')){ return redirect(url('/'));  }
        $carType=CarType::find($id);
        return view('maintenance.carType.edit',['carType'=>$carType]);
    }

    public function update(Request $request, $id)
    {
        if(!Gate::allows('车型-编辑')){ return redirect(url('/'));  }
        $this->validatorCarType($request,$id)->validate();
        $data=$request->input('CarType');
        $carType=CarType::find($id);
        $carType->fill($data);
        if ($carType->save()){
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/carType')->with('successTip','车型“'.$request->input('CarType.name').'”修改成功');
        }
    }

    public function destroy($id)
    {
        if(!Gate::allows('车型-删除')){ return redirect(url('/'));  }
        $carType=CarType::find($id);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($carType),Auth::user()['id']);
        $result=$carType->delete();
        return ['success'=>$result];
    }

    public function get()
    {
        return CarType::query()->select("id","name","model")->get();
    }

    protected  function validatorCarType(Request $request,$id){
        if ($id){$name=$id;}
        $validator=Validator::make($request->input(),[
            'CarType.name'=>['required','max:50',isset($name)?"unique:car_types,name,$name":'unique:car_types,name'],
            'CarType.model'=>'nullable|max:50',
            'CarType.length'=>'nullable|min:0',
            'CarType.load'=>'nullable|min:0',
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 字符过多或数值过大',
            'min'=>':attribute 不得为负',
            'unique'=>':attribute 已存在',
        ],[
            'CarType.name'=>'车辆名称',
            'CarType.model'=>'车辆型号',
            'CarType.length'=>'车辆长度',
            'CarType.load'=>'车辆载重',
        ]);
        return $validator;
    }

    public function batchInsert()
    {
        $arr = request("arr");
        if (!$arr)$this->error("非法参数");
        DB::transaction(function()use($arr){
            $cars = CarType::query()->whereIn("name",$arr)->lockForUpdate()->get()->toArray();
            $result = array_diff($arr,array_column($cars,"name"));
            if ($result){
                foreach ($result as &$r)$r = ["name"=>$r];
                CarType::query()->insert($result);
            }
        });
        $this->success(CarType::query()->select("id","name")->whereIn("name",$arr)->get());
    }
}
