<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\Services\common\BatchUpdateService;
use App\Unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class UnitController extends Controller
{
    use AsyncResponse;
    public function index()
    {
        if(!Gate::allows('计量单位-查询')){ return redirect(url('/'));  }
        $units=Unit::query()->orderBy("sequence")->paginate(50);
        return view('maintenance.unit.index',['units'=>$units]);
    }

    public function destroy($id)
    {
        if(!Gate::allows('计量单位-删除')){ return redirect(url('/'));  }
        Unit::destroy($id);
        return ['success'=>true];
    }

    public function save()
    {
        $this->gate("计量单位-录入");
        $errors = $this->validatorUnit(request(),request("id"))->errors();
        if (count($errors)>0)$this->success(["errors"=>$errors]);

        $obj = ["name"=>request("name"),"sequence"=>request("sequence") ?? 0];
        if (request("id")){
            Unit::query()->update($obj);
            $this->success();
        }
        $this->success(Unit::query()->create($obj));
    }

    public function sort()
    {
        $this->gate("计量单位-录入");

        if (request("update") && count(request("update"))>1)app(BatchUpdateService::class)->batchUpdate("units",request("update"));
        $this->success();
    }

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

    public function getUnits()
    {
        return ["success"=>true,"data"=>app("UnitService")->getSelection()];
    }
}
