package com.ruoyi.web.modules.account.service.impl;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.account.constant.MemberConstants;
import com.ruoyi.web.modules.account.service.IMemberSmsService;

/**
 * 短信验证码（开发环境写入 Redis；生产对接短信网关）
 */
@Service
public class MemberSmsServiceImpl implements IMemberSmsService
{
    @Autowired
    private RedisCache redisCache;

    @Override
    public void sendCode(String mobile)
    {
        validateMobile(mobile);
        String code = String.format("%06d", new Random().nextInt(999999));
        redisCache.setCacheObject(MemberConstants.REDIS_SMS_PREFIX + mobile, code,
                MemberConstants.SMS_EXPIRE_MINUTES, TimeUnit.MINUTES);
    }

    @Override
    public boolean verifyCode(String mobile, String code)
    {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code))
        {
            return false;
        }
        String cached = redisCache.getCacheObject(MemberConstants.REDIS_SMS_PREFIX + mobile);
        return code.equals(cached);
    }

    private void validateMobile(String mobile)
    {
        if (StringUtils.isEmpty(mobile))
        {
            throw new ServiceException("请输入手机号");
        }
        if (!mobile.matches("^1\\d{10}$"))
        {
            throw new ServiceException("手机号格式不正确");
        }
    }
}
