<?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 postRules()
    {
        return [
            'phone' => 'bail|required|regex:/^1[3456789][0-9]{9}$/|unique:users',
            'password' => 'required|string|min:6',
            'code' => 'required|string',
        ];
    }

    protected function putRules()
    {

        //找回密码
        if (strpos($this->path(), 'password') > 0) {
            return [
                'phone' => 'bail|required|regex:/^1[3456789][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->encryptedData, $userId);
            if ($data && $data['purePhoneNumber']) {
                //$this->request->add(['phone' => $data['purePhoneNumber']]);
                $this['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[3456789][0-9]{9}$/|unique:users',
            'sex' => 'in:0,1,2',
            'code' => 'nullable'.$needVerifyPhone.'|string',
        ];
    }

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

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