package com.bonus.common.security.service;

import com.bonus.common.core.constant.CacheConstants;
import com.bonus.common.core.exception.CaptchaException;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.VerificationCodeUtils;
import com.bonus.common.core.utils.sms.SmsUtils;
import com.bonus.common.redis.service.RedisService;
import com.bonus.common.security.config.VerificationCodeConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.bonus.common.core.utils.VerificationCodeUtils.CodeType.NUMERIC;

/**
 * @author bonus
 */
@Component
public class SmsService {
    @Resource
    private VerificationCodeConfig verificationCodeConfig;
    @Resource
    private RedisService redisService;

    /**
     * 生成手机验证码
     *
     * @return AjaxResult
     * @throws CaptchaException 自定义captcha 异常
     */
    public void sendSimplePhone(String to) {
        if (StringUtils.isEmpty(to)) {
            throw new CaptchaException("手机号不能为空");
        }
        String code = VerificationCodeUtils.generateVerificationCode(NUMERIC);
        String str = verificationCodeConfig.getContent().replace("<code>", code);
        str = str.replace("<time>", verificationCodeConfig.getTime().toString());
        String s = SmsUtils.smsToken(to, str, "");
        if (StringUtils.isNotEmpty(s)) {
            if (s.contains("ok")) {
                String verifyKey = CacheConstants.VERIFICATION_CODE + StringUtils.nvl(to, "");
                redisService.setCacheObject(verifyKey, code, verificationCodeConfig.getTime(), TimeUnit.MINUTES);
            } else {
                throw new CaptchaException("获取短信失败");
            }
        } else {
            throw new CaptchaException("获取短信失败");
        }
    }
}
