<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RoleController extends Controller
{
    //角色列表
    public function index(Request $request){
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
        $count=Role::count();
        $list=Role::skip($num)->take($page_size)->get();
        return $this->success_list($list,'',$count);
    }
    //添加角色
    public function add(Request $request){
        $rules=[
            'name'=>'required|max:32'
        ];
        $message=[
            'name.required'=>'用户名不能为空.',
            'name.max'=>'用户名不能大于32个字符.'
        ];
        $validator = Validator::make($request->input(),$rules,$message);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $admin=new Role();
        $admin->name=$request->input('name');
        $res=$admin->save();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //修改角色
    public function edit(Request $request){
        $rules=[
            'name'=>'required|max:32'
        ];
        $message=[
            'name.required'=>'用户名不能为空.',
            'name.max'=>'用户名不能大于32个字符.'
        ];
        $validator = Validator::make($request->input(),$rules,$message);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        if(Role::where('name',$request->input('name'))->value('id') != $request->input('id')){
            return $this->error('450001','角色名称已存在');
        }
        $admin=Role::find($request->input('id'));
        $admin->name=$request->input('name');
        $res=$admin->save();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //删除角色
    public function destroy(Request $request){
        $res=Role::where('id',$request->input('id'))->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
}
