<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Hash;

class AdminUserController extends Controller
{
    //管理员列表
    public function list()
    {
        $admin = DB::table('adminuser') -> get();
        $rule = DB::table('rule') -> where('status',1) -> get();
        return view('Admin.adminuser',['admin'=>$admin,'rule' => $rule]);
    }
    //状态
    public function status(Request $req)
    {
        if(!$req -> id){
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        $status = DB::table('adminuser') -> where('id',$req -> id) -> value('status');
        if($status){
            $is = DB::table('adminuser') -> where('id',$req -> id) -> update(['status'=>0]);
        }else{
            $is = DB::table('adminuser') -> where('id',$req -> id) -> update(['status'=>1]);
        }
        return $is ? ['code'=> '1000','msg'=>'操作完成'] : ['code'=> '1002','msg'=>'操作失败']; 
    }
    //删除
    public function delete(Request $req)
    {
        if(!$req -> id){
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        $is = DB::table('adminuser') -> where('id',$req -> id) -> delete();
        return $is ? ['code'=> '1000','msg'=>'删除成功'] : ['code'=> '1002','msg'=>'删除失败'];
    }
    //创建账户
    public function create(Request $req)
    {
        if(in_array('',$req -> all())) {
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        $adminuser = [];
        $adminuser['username'] = $req -> username;
        $adminuser['password'] = Hash::make($req -> password);
        $adminuser['rule'] = $req -> rule;
        $adminuser['status'] = 1;
        $is = DB::table('adminuser') -> insert($adminuser);
        return $is ? ['code'=> '1000','msg'=>'添加完成'] : ['code'=> '1002','msg'=>'添加失败'];
    }
    //管理员修改
    public function update(Request $req)
    {
        if(!$req -> id){
            return ['code'=>'10001','msg'=>'参数错误'];
        }
        if($req -> password){
            $user['password'] = Hash::make($req -> password);
        }
        $user['username'] = $req -> username;
        $user['rule'] = $req -> rule;
        $is = DB::table('adminuser') -> where('id',$req -> id) -> update($user);
        return $is ? ['code'=> '1000','msg'=>'修改完成'] : ['code'=> '1002','msg'=>'修改失败'];
    }
}
