<?php

namespace App\Http\Requests;

use Route;
use App\Http\Requests\Request;

class UserRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
            $rules = [
                'name'     => 'required|min:3',
                'email'    => 'required|email|unique:users',
                'password' => 'required|confirmed|min:3',
                'role_id'  => 'required',
            ];

            if ($this->isMethod('patch') || $this->isMethod('put')) {
                $rules = array_except($rules, ['password']);
                $rules['email'] = 'unique:users,email,'.$this->route('user');
            }

            if (Route::currentRouteName() == 'admin.user.update-pwd') {
                $rules = array_except($rules, ['role_id']);
                $rules['password'] = 'confirmed|min:3';
            }

            return $rules;
    }

    public function messages()
    {
        return [
            'name.required'      => '用户名不能为空',
            'email.required'     => '邮箱不能为空',
            'email.email'        => '邮箱格式不对',
            'email.unique'       => '邮箱已经存在',
            'password.required'  => '密码不能为空',
            'password.confirmed' => '两次密码不匹配',
            'role_id.required'   => '请选择用户角色',
        ];
    }
}
