<?php

namespace Jindouyun\Cache;

use http\Exception;
use Mall\Framework\Factory;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;

class SmsVerification
{
    private $cache;
    protected $registerSmsCountKey = 'registerSmsCount_'; //当天每个手机号发送验证码次数
    protected $key = '';
    protected $userRegisterSmsCodeExpire = 300;//短信验证码过期时间
    protected $registerSms = 'registerSms'; //当前手机号发送的验证码

    public function __construct()
    {
        $this->key = $this->registerSmsCountKey . date('Y-m-d', time());
        $this->cache = Factory::cache('default');
    }

    /**
     * 缓存用户注册时发送的短信验证码
     * @param $mobile
     * @param $mobileCode
     * @return ResultWrapper
     */
    public function userMobileCodeCache($mobile, $mobileCode)
    {
        if (empty($mobileCode)) {
            return ResultWrapper::fail('要缓存的数据为空', ErrorCode::$paramError);
        }

        $result = $this->cache->set($this->registerSms . '::' . $mobile, $mobileCode, $this->userRegisterSmsCodeExpire);

        if ($result) {
            //增加当天用户发送短信次数
            $returnData = $this->cache->zincrby($this->key, 1, $mobile);
            if ($returnData) {
                $this->cache->expire($this->key, 86400);
            }
            return ResultWrapper::success('用户注册手机验证码写入缓存成功');
        } else {
            return ResultWrapper::fail('用户注册手机验证码写入缓存失败', ErrorCode::$redisWriteError);
        }
    }

    /**
     * 获取指定手机号的短信验证码
     * @param $mobile
     * @return string
     * @throws \Exception
     */
    public function getMobileCode($mobile)
    {
        if (!$mobile) {
            return '';
        }

        $result = Factory::cache('default')->get($this->registerSms . '::' . $mobile);

        if (!$result) {
            return '';
        }

        return $result;
    }

    /**
     * 查询当天用户发送短信次数
     * @param $mobile
     * @return mixed
     */
    public function getRegisterSmsCount($mobile)
    {
        return $this->cache->zscore($this->key, $mobile);
    }
}