package com.youchain.modules.security.service;

import cn.hutool.core.util.RandomUtil;
import com.youchain.modules.security.config.bean.LoginProperties;
import com.youchain.utils.RedisUtils;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;

@Component
@Slf4j
public class CodeUtils {
    @Resource
    private  RedisUtils redisUtils;

    private  long idleTime=86400;

    private  final String time_yyMMdd="yyMMdd";
    private  final String time_yyyyMMdd="yyyyMMdd";



    public synchronized String  getCode_yyMMdd(String key, int len ){
      return getCode(key,time_yyMMdd,len);
    }

    public synchronized String  getCode_yyyyMMdd(String key, int len ){
        return getCode(key,time_yyyyMMdd,len);
    }

    public synchronized String  getCode(String key, String parm,int len){
        String key_str =new SimpleDateFormat(parm).format(Calendar.getInstance().getTime());
        String  last_index= (String)redisUtils.hget(key,key_str);
        log.info("last_value："+last_index);
        String  value_end="1";
        if( last_index ==null ||last_index.length()<=0){
            value_end="1";
        }else{
            value_end=(Integer.parseInt(last_index)+1)+"";
        }
        while(value_end.length()<len){
            value_end="0"+value_end;
        }
        String value= key+key_str+value_end;
        long time = idleTime + RandomUtil.randomInt(900, 1800);

        boolean f=redisUtils.hset(key, key_str, value_end, time);
        log.info("save:"+value+"--" +""+f);
        if(f){
            log.info("return:"+value);
            return value;
        }else{
            log.error("Reids connet is err");
            return null;
        }


    }
}
