package com.ruoyi.cai.manager;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.cai.constant.RedisConstant;
import com.ruoyi.cai.enums.CodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CodeManager {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public String getKey(CodeEnum codeEnum,String phone){
        return String.format(RedisConstant.CODE_REDIS,codeEnum.name(),phone);
    }

    public String put(CodeEnum codeEnum,String phone){
        String code = RandomUtil.randomNumbers(6);
        String key = getKey(codeEnum, phone);
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        return code;
    }

    public boolean check(CodeEnum codeEnum,String phone,String code){
        String key = getKey(codeEnum, phone);
        String val = redisTemplate.opsForValue().get(key);
        if(val == null){
            return false;
        }
        return val.equals(code);
    }

}
