<?php

namespace app\api\validate;

use think\Validate;

class UserValidate extends BaseValidate
{
    protected $rule =   [
        'name'  => 'require',
        'mobile'   => 'require|mobile',
        'password'=>'require',
        'code'=>'require',
        'token'=>'require',
        'str'=>'require',
        'confirm_password' => 'require|checkPasswordEqual',
        'updateField'=>'require|in:username,realname,sex,headico,description,email,qq,wechat',
        'updateValue'=>'require',
        'zfb'=>'require',
        'realname'=>'require',
        'idcard'=>'require',
        'idcard_q'=>'require',
        'idcard_h'=>'require',
        'amount'=>'require|chenckAmount',
        'txType'=>'require',
    ];

    protected $message  =   [
        'name.require' => '名称必须',
        'mobile.require'   => '手机号不能为空',
        'mobile.mobile'  => '手机号格式不正确',
        'password.require'   => '密码必须',
        'code.require'   => '验证码必须',
        'token.require'   => 'token必须',
        'str.require'   => '必填项不能为空',
        'confirm_password.checkPasswordEqual' => '两次输入的密码不一致',
        'updateField.require'   => '必填项不能为空',
        'updateField.in'   => '范围不合法',
        'amount.require'   => '金额不能为空',
        'amount.chenckAmount'   => '金额不合法',
    ];

    protected function checkPasswordEqual($value, $rule, $data)
    {
        return $value === $data['password'];
    }

    protected function chenckAmount($value, $rule, $data)
    {
        $decimal = $rule['decimal'] ?? 2;

        if (!is_numeric($value)) {
            return false;
        }

        if ($value < 0) {
            return false;
        }

        if (strpos((string)$value, '.') !== false) {
            $decimalPart = explode('.', (string)$value)[1];
            if (strlen($decimalPart) > $decimal) {
                return false;
            }
        }


        return true;
    }
}