package com.xueyi.common.sms.service;

import com.xueyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * spring sms 工具类
 *
 * @author xueyi
 **/
@Component
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public class SmsService {

    @Autowired
    private RedisService redisService;

    /**
     * @Author yangkai
     * @Description //发送验证码，取时间戳后四位
     * @Date 2023/4/26
     * @Param
     * @return
     **/
    public String sendCode(){
        Set<String> codes = new HashSet<>();
        String code = "";
        //确保不重复
        while(true) {
            code = String.valueOf(System.currentTimeMillis());
            code = code.substring(9);
            if (!redisService.hasKey("codes:"+code)) {
                redisService.setCacheObject("codes:"+code, 1);
                redisService.expire("codes:"+code, 600);//设置十分钟过期
                break;
            }
        }
        return code;
    }
    /**
     * @Author yangkai
     * @Description //验证验证码是否合法
     * @Date 2023/4/26
     * @Param
     * @return
     **/
    public boolean checkCode(String code) {
        if (redisService.hasKey("codes:"+code)) {
            redisService.expire("codes:"+code, 1);//使用后立马过期
           return true;
        }
        return false;
    }
}