package com.zzwtec.third.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;

import static java.util.concurrent.TimeUnit.MINUTES;

/**
 * create by Jomchen on 2018/12/3
 * 验证码处理类
 */
@Service
public class VerifyCodeComponent {

    @Autowired
    @Qualifier("stringRedisTemplate")
    private RedisTemplate<String, String> stringRedisTemplate;

    /**
     * 获取验证redis key
     * @param sessionId
     * @return
     */
    public String getVerifyCodeRedisKey(String sessionId) {
        return RedisPrefixAndConstant.VERIFY_CODE_PREFIX + sessionId;
    }

    /**
     * 生成验证码 随机码
     * @param simple 是否要简单的验证码
     * @param length 验证码长度
     * @return
     */
    public String makeVerifyNum(boolean simple, int length){
        final char[] legalChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        short len = 62;
        if(simple){
            len = 10;
        }
        for (int i = 0; i < length; i++) {
            char rand = legalChars[random.nextInt(len)];
            sb.append(rand);
        }
        String sjm = sb.toString();
        return sjm;
    }

    /**
     * 创建验证码
     *
     * @param sessionId
     * @return
     */
    public String buildVerifyCode(String sessionId) {
        String key = getVerifyCodeRedisKey(sessionId);
        String code = makeVerifyNum(true, 4);
        stringRedisTemplate.opsForValue().set(key, code, 5, MINUTES);
        return code;
    }

}
