<?php

namespace App\Http\Controllers;

use App\Unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class UnitsController extends Controller
{

    public function index()
    {
        if(!Gate::allows('计量单位-查询')){ return redirect(url('/'));  }
        $units=Unit::paginate(50);
        return view('maintenance.unit.index',['units'=>$units]);
    }

    public function create()
    {
        if(!Gate::allows('计量单位-录入')){ return redirect(url('/'));  }
        return view('maintenance.unit.create');
    }


    public function store(Request $request)
    {
        if(!Gate::allows('计量单位-录入')){ return redirect(url('/'));  }
        $id=false;
        $this->validatorUnit($request,$id)->validate();
        $units=$request->input('Unit');
        if(Unit::create($units)){
            $this->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/unit')->with('successTip','新计量单位“'.$request->input('Unit.name').'”添加成功');
        };
    }

    public function edit($id)
    {
        if(!Gate::allows('计量单位-编辑')){ return redirect(url('/'));  }
        $unit=Unit::find($id);
        return view('maintenance.unit.edit',['unit'=>$unit]);
    }

    public function update(Request $request, $id)
    {
        if(!Gate::allows('计量单位-编辑')){ return redirect(url('/'));  }
        $this->validatorUnit($request,$id)->validate();
        $data=$request->input('Unit');
        $unit=Unit::find($id);
        $unit->fill($data);
        if ($unit->save()){
            $this->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
            return redirect('maintenance/unit')->with('successTip','计量单位“'.$request->input('Unit.name').'”修改成功');
        }
    }

    public function destroy($id)
    {
        if(!Gate::allows('计量单位-删除')){ return redirect(url('/'));  }
        $unit=Unit::find($id);
        $this->log(__METHOD__,__FUNCTION__,json_encode($unit),Auth::user()['id']);
        $result=$unit->delete();
        return ['success'=>$result];
    }

    protected function validatorUnit(Request $request,$id){
        if ($id){$name=$id;}
        $validator=Validator::make($request->input(),[
            'Unit.name'=>['required','max:10',isset($name)?"unique:units,name,$name":'unique:units,name'],
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 过长',
            'unique'=>':attribute 已存在',
        ],[
            'Unit.name'=>'计量单位名称',
        ]);
        return $validator;
    }
}
