package com.ruoyi.common.redis.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

import static org.apache.commons.lang3.StringUtils.leftPad;

@Component
public class ReportNumberUtils {

    @Resource
    private RedisTemplate redisTemplate;

    //传入制定的key和prefix
    public String getSeqNo(String key, String prefix) {
        return getSeqNoSize(key, prefix, 5);
    }

    public String getSeqNoSize(String key, String prefix, Integer size) {
        if (Objects.isNull(size)) {
            // size 序列号位数
            size = 5;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        //设置过期时间，这里设置为当天的23:59:59
        Date expireDate = calendar.getTime();
        //返回当前redis中的key的最大值
        Long seq = generate(redisTemplate, key, expireDate);
        //获取当天的日期，格式为yyyyMMdd
        String date = new SimpleDateFormat("yyyyMMdd").format(expireDate);
        //生成八为的序列号，如果seq不够八位，seq前面补0，
        //如果seq位数超过了八位，那么无需补0直接返回当前的seq
        String sequence = leftPad(seq.toString(), size, "0");
        if (prefix == null) {
            prefix = "";
        }
        //拼接业务编号
        String seqNo = prefix + date + sequence+"100";
        return seqNo;
    }

    public String getOrderSeqNo(String key, String prefix, Integer size) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        //设置过期时间，这里设置为当天的23:59:59
        Date expireDate = calendar.getTime();
        //返回当前redis中的key的最大值
        Long seq = generate(redisTemplate, key, expireDate);
        //获取当天的日期，格式为yyyyMMdd
        String date = new SimpleDateFormat("yyyyMMdd").format(expireDate);
        //生成八为的序列号，如果seq不够八位，seq前面补0，
        //如果seq位数超过了八位，那么无需补0直接返回当前的seq
        String sequence = leftPad(seq.toString(), size, "0");
        if (prefix == null) {
            prefix = "";
        }
        //拼接业务编号
        String seqNo = prefix + date + sequence;
        return seqNo;
    }

    public static long generate(RedisTemplate<?,?> redisTemplate,String key,Date expireTime) {
        //RedisAtomicLong为原子类，根据传入的key和redis链接工厂创建原子类
        RedisAtomicLong counter = new RedisAtomicLong(key,redisTemplate.getConnectionFactory());
        //设置过期时间
        counter.expireAt(expireTime);
        //返回redis中key的值，内部实现下面详细说明
        return counter.incrementAndGet();
    }
}


