<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\User;
use App\Models\Role;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class AdminController 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=Admin::count();
        $list=Admin::with('role:id,name')->skip($num)->take($page_size)->get();
        return $this->success_list($list,'',$count);
    }
    //添加管理员
    public function add(Request $request){
        return $this->error('450001','无权限添加');
        $rules=[
            'name'=>[
                'required',
                Rule::unique('admins')
                    ->where(function ($query) {
                        $query->where('deleted_at', null);
                    }),
                'between:5,12'
            ],
            'password'=>'required|between:6,12',
            'role_id'=>'required',
            'mobile'=>'required_if:role_id,23|size:11',
        ];
        $messages=[
            'name.required'=>'账号不能为空.',
            'name.between'=>'账号长度应为5-12个字符.',
            'name.unique'=>'账号名已存在.',
            'password.required'=>'密码不能为空.',
            'password.between'=>'密码长度应为6 -12个字符.',
            'role_id.required'=>'请选择角色.',
            'mobile.size'=>'手机号长度应为11个字符.',
            'mobile.required_if'=>'客服手机号必填'
        ];
        $validator = Validator::make($request->input(),$rules,$messages);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        if(Admin::where('name',$request->input('name'))->first()){
            return $this->error('450001','管理员名称已存在');
        }
        $res=Admin::create([
            'name'=>$request->input('name'),
            'role_id'=>$request->input('role_id'),
            'password'=>Hash::make($request->input('password')),
            'mobile'=>$request->input('mobile'),
            'status' => 1
        ]);
        if($res){
            if(empty(User::find($res->id))){
                User::create(['id'=>$res->id,
                    'name'=>'user_'.$res->id.'(关键用户勿动)',
                    'nickname'=>'user_'.$res->id,
                    'store_id'=>0,
                    'status'=>1
                ]);
            }
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //修改管理员
    public function edit(Request $request){
        $rules=[
            'name'=>'required|max:32',
            'password'=>'sometimes|required|min:6|max:18',
            'role_id'=>'required',
            'mobile'=>'required_if:role_id,23|size:11'
        ];
        $message=[
            'name.required'=>'用户名不能为空.',
            'name.max'=>'用户名不能大于32个字符.',
            'password.required'=>'密码不能为空.',
            'password.min'=>'密码小于6个字符.',
            'password.max'=>'密码不能大于18个字符.',
            'role_id.required'=>'请选择角色.',
            'mobile.size'=>'手机号长度应为11个字符.',
            'mobile.required_if'=>'客服手机号必填'
        ];
        $validator = Validator::make($request->input(),$rules,$message);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $admin_id=Admin::where('name',$request->input('name'))->value('id');
        if($admin_id && $admin_id!=$request->input('id')){
            return $this->error('450001','管理员名称已存在');
        }
        $admin=Admin::find($request->input('id'));
        $admin->name=$request->input('name');
        $admin->role_id=$request->input('role_id');
        $admin->mobile=$request->input('mobile');
        if($request->has('password') && !empty($request->input('password'))){
            $admin->password=Hash::make($request->input('password'));
        }
        $res=$admin->save();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //删除管理员
    public function destroy(Request $request){
        $res=Admin::where('id',$request->input('id'))->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //禁用管理员
    public function disabled(Request $request){
        $id=$request->input('id');
        $status=Admin::where('id',$id)->value('status');
        $status=$status==1?2:1;
        $res=Admin::where('id',$id)->update(['status'=>$status]);
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //获取角色
    public function getAllRoles(){
        $role=Role::select('id','name')->orderBy('id','desc')->get();
        return $this->success($role);
    }
    /*添加 角色*/
    public function uploadRole(Request $request){
        $rules=[
            'name' => 'required|max:32|unique:roles',
            'permissions' => 'required',
        ];
        $messages=[
            'name.required'=>'角色名称不能为空.',
            'name.max'=>'角色名称不能超过32个字符.',
            'name.unique'=>'角色名称已存在.',
            'permissions.required'=>'请选择角色权限.',
        ];
        $validator = Validator::make($request->all(),$rules,$messages);
        if ($validator->fails()) {
            return $this->error('400013',$validator->errors()->first());
        }
        $result=Role::create([
            'name'=>$request->post('name'),
            'permissions'=>$request->post('permissions'),
            'desc'=>$request->post('desc'),
            'disable'=>0,
        ]);
        if($result->id){
            Log::info('管理员:'.Auth::user()->name.'(id='.Auth::user()->id.')添加（'.$request->post('name').'）角色成功');
            return $this->success([]);
        }
        return $this->error();
    }
    /* 角色禁用  */
    public function disableRole(Request $request){
        $role=Role::find($request->post('id'));
        $role->disable=($role->disable==0)?'1':'0';
        $row=$role->save();
        if($row){
            Log::info('管理员:'.Auth::user()->name.'(id='.Auth::user()->id.')禁用了（'.$role->name.'）角色');
            return $this->success([]);
        }
        return $this->error();
    }
    /*修改角色*/
    public function updateRole(Request $request){
        $input=$request->all();
        $rules=[
            'name' => 'required|max:32',
            'permissions' => 'required',
        ];
        $messages=[
            'name.required'=>'角色名称不能为空.',
            'name.max'=>'角色名称不能超过32个字符.',
            'permissions.required'=>'请选择角色权限.',
        ];
        $validator = Validator::make($input,$rules,$messages);
        if ($validator->fails()) {
            return $this->error('400013',$validator->errors()->first());
        }
        $role=Role::where('name',$input['name'])->first();
        if($role){
            if($role->id!=$input['id']){
                return $this->error('400012','角色名称已存在.');
            }
        }
        $roles=Role::find($request->id);
        $roles->name=$request->name;
        $roles->permissions=$request->permissions;
        $roles->desc=$request->desc;
        $result=$roles->save();
        if($result){
            Log::info('管理员:'.Auth::user()->name.'(id='.Auth::user()->id.')修改了（'.$role->name.'）角色');
            return $this->success([]);
        }
        return $this->error();
    }
}
