<?php

namespace Modules\Base\Http\Requests;

use Modules\Base\Services\OpenloginService;

class UserRequest extends BaseRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch ($this->method()) {
            case 'POST':
                return [
                    'phone' => 'bail|required|regex:/^1[345789][0-9]{9}$/|unique:users',
                    'password' => 'required|string|min:6',
                    'code' => 'required|string',
                ];
                break;
            case 'PUT':
                //找回密码
                if (strpos($this->path(), 'password') > 0) {
                    return [
                        'phone' => 'bail|required|regex:/^1[345789][0-9]{9}$/|exists:users',
                        'password' => 'required|string|min:6',
                        'code' => 'required|string',
                    ];
                }

                //更新资料
                $user = \Auth::user();
                $userId = $user->id;

                $needVerifyPhone = $user->phone ? '|required_with:phone' : '';

                //当用户手机号为空，且传了encryptedData 和 iv 参数 ，试图解析手机号
                if (!$user->phone && $this->encryptedData && $this->iv) {
                    $data = app(OpenloginService::class)->decryptData($this->iv, $this->encryptData, $userId);
                    if ($data && $data['purePhoneNumber']) {
                        $this->request->add(['phone' => $data['purePhoneNumber']]);
                    }
                }

                return [
                    'name' => 'between:1,25',
                    'email' => 'email|unique:users,email,'.$userId,
                    //'introduction' => 'max:80',
                    'file_id' => 'exists:files,id,type,avatar,user_id,'.$userId,
                    'ext' => 'array',
                    'old_password' => 'bail|required_with:password|string|min:6|check_password:'.$user->getAuthPassword(),
                    'password' => 'string|min:6',
                    'phone' => 'bail|regex:/^1[345789][0-9]{9}$/|unique:users',
                    'sex' => 'in:0,1,2',
                    'code' => 'nullable'.$needVerifyPhone.'|string',
                ];
                break;
        }
    }

    public function attributes()
    {
        return [
            'old_password' => '旧密码',
        ];
    }

    public function messages()
    {
        return [
          'old_password.required_with' => '旧密码不能为空',
        ];
    }
}
