<?php

namespace App\Http\Controllers;

use App\Authority;
use App\Role;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if(!Gate::allows('角色-查询')){ return redirect(url('/'));  }
        $query = Role::with('authorities');
/*        if($request->has('user')){
            $user = $request->input('user');
            $query->whereHas('users',function($query) use ($user){
                $query->where('name','like',$user);
            });
        }*/
        if($request->has('role')){
            $role=$request->input('role');
            if (strpos($role, ',') || strpos($role, '，') || strpos($role, ' ')) {
                $arr = array_filter(preg_split('/[,， ]+/is', $role));
                $query->whereIn('name', $arr);
                unset($role);
            } else {
                $query->where('name','like',$role.'%');
            }
        }
        $roles= $query->orderBy('id','desc')->paginate(35);
        return view('maintenance.role.index',['roles'=>$roles]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!Gate::allows('角色-录入')){ return redirect(url('/'));  }
        $authoritiesAll=Authority::orderBy('alias_name','desc')->get();
        $authoritiesAll = Authority::filterRecycle($authoritiesAll);
        return view('maintenance.role.create',compact('authoritiesAll'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        if(!Gate::allows('角色-录入')){ return redirect(url('/'));  }
        $this->validatorCreate($request->all())->validate();
        $role=new Role($request->all());
        $role->save();
        $authorityIds=$request->input('authority')??'';
        if($authorityIds){
            $authorityIdArr=explode(',',$authorityIds);
            $role->authorities()->sync($authorityIdArr);
        }

        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/role/create')->with('successTip',"成功录入角色“{$request->input('name')}”");
    }
    protected function validatorCreate(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:50', 'unique:roles'],
        ]);
    }
    protected function validatorUpdate(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:50'],
        ]);
    }
    /**
     * Display the specified resource.
     *
     * @param Role $role
     * @return Response
     */
    public function show(Role $role)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Role $role
     * @return Response
     */
    public function edit(Role $role)
    {
        if(!Gate::allows('角色-编辑')){ return redirect(url('/'));  }
        $authoritiesAll=Authority::orderBy('alias_name','desc')->get();
        $authoritiesAll = Authority::filterRecycle($authoritiesAll);
        $authorities=$role->authorities()->get();
        return view('maintenance.role.edit',compact('role','authorities','authoritiesAll'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Role $role
     * @return Response
     */
    public function update(Request $request, Role $role)
    {
        if(!Gate::allows('角色-编辑')){ return redirect(url('/'));  }
        $this->validatorUpdate($request->all())->validate();
        $role->fill($request->all());
        $role->update();
        $authorityIds=$request->input('authority')??'';
        if($authorityIds){
            $authorityIdArr=explode(',',$authorityIds);
            $role->authorities()->sync($authorityIdArr);
        }else{
            $role->authorities()->sync([]);
        }
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/role/')->with('successTip',"成功修改角色“{$role['name']}”！");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Role $role
     * @return array|Response
     * @throws Exception
     */
    public function destroy(Role $role)
    {
        if(!Gate::allows('角色-删除')){ return redirect(url('/'));  }
        app('LogService')->log(__METHOD__,__FUNCTION__,$role->toJson(),Auth::user()['id']);
        $re=$role->delete();
        return ['success'=>$re];
    }
}
