<?php

namespace App\Http\Controllers\Admin;

use App\Model\Job;
use App\Model\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class UserController extends CommonController
{
//    用户列表
    public function user_list()
    {
        $data = User::orderby('id','asc')->paginate(10);
        return view('admin.user.userlist',compact('data'));
    }

//    编辑用户
    public function edit($user_id)
    {
        $data = User::find($user_id);
        $user_job = Job::all();
        return view('admin.user.edit',['data'=>$data,'user_job'=>$user_job]);
    }
    
//    更新用户信息
    public function update($user_id)
    {
        $input = Input::except('_token','_method');
        $re = User::find($user_id)->update($input);
        if($re){
            return redirect('/user_list');
        }else{
            return back()->with('errors','用户信息更新失败，请稍后重试!');
        }
    }

    public function create()
    {
        return view('admin.user.add_user');
    }

    public function store()
    {
        $input = Input::except('_token');
        $rules = [
            'name'=>'required',
            'pswd'=>'required',
            'surname'=>'required'
        ];
        $msg = [
            'name.required'=>'登录名不能为空！',
            'pswd.required'=>'密码不能为空！',
            'surname.required'=>'姓名不能为空！'
        ];
        $validator = Validator::make($input,$rules,$msg);
        if($validator->passes()){
            $re = User::create($input);
            if($re){
                return redirect('/user_list');
            }else{
                return back()->with('errors','未知错误，请稍后重试！');
            }
        }else{
            return back()->withErrors($validator);
        }
    }

    public function destroy($user_id)
    {
        $re = User::where('id',$user_id)->delete();
        if($re){
            $data = [
                'status'=>1,
                'msg' => '删除成功！'
            ];
        }else{
            $data =[
                'status'=>0,
                'msg' => '删除失败，请刷新重试！'
            ];
        }
        return $data;
    }
}
