<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\api\validate;

use app\common\library\utils\Check;
use think\Validate;
use app\common\model\Users as UsersModel;

/**
 * @package app\api\validate
 * @class Register
 * @author xzncit 2024-01-25
 */
class Register extends Validate {

    protected $rule = [
        'username'          => 'require|checkUsername',
        'password'          => 'require|checkPassword|min:6|max:20',
        'confirm_password'  => 'require|confirm:password'
    ];

    protected $message  =   [
        'username.require'          => '请输入帐号',
        'password.require'          => '请输入密码',
        'password.min'              => '密码长度不能少于6个字符',
        'password.max'              => '密码长度不能超过20个字符',
        'confirm_password.require'  => '请输入确认密码',
        'confirm_password.confirm'  => '您输入的两次密码不相等'
    ];

    /**
     * @var array
     */
    protected $scene = [];

    /**
     * 检查用户名称是否存在
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool|string
     * @throws \think\db\exception\DbException
     */
    protected function checkUsername($value, $rule, $data=[]){
        if(UsersModel::where("username",$value)->count()){
            return "您填写的帐号名称已存在";
        }

        if(!Check::username($value,5,15)){
            return "帐号名称只能包含a-z0-9-_字符,并且长度在5-15个字符间";
        }

        if(preg_match("/(\s)/i",$value)){
            return "帐号名称不能包含空格字符";
        }

        return true;
    }

    /**
     * 检查密码
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool|string
     */
    protected function checkPassword($value, $rule, $data=[]){
        if(preg_match("/(\s)/i",$value)){
            return "您填写的密码包含空格字符";
        }

        return true;
    }

}