package cn.myapps.util.serial.number;

import cn.myapps.common.util.SpringApplicationContextUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class GenerateSerialNumber {
    StringRedisTemplate redisTemplate;

    public GenerateSerialNumber() {
        this.redisTemplate = ((StringRedisTemplate) SpringApplicationContextUtil.getBean(StringRedisTemplate.class));
    }

    /**
     * 根据业务类型获取流水号
     * @param ywlx
     * @return
     */
    public String getSerialNumber(String ywlx){
        if(!SerialNumberConstants.Bapx.BAPX_YWLX.equals(ywlx) && !SerialNumberConstants.Bapx.BAPX_YWLX_JYZ.equals(ywlx) ) {
            return null;
        }

        long sequence = incr(ywlx);
        String seq = getSequence(sequence,SerialNumberConstants.Bapx.BAPX_LENTH);
        return seq;
    }


    /**
     * 根据前缀获取流水号
     * @param headText(前缀) isYear(是否需要年份) isMonth(是否需要月份) isDay(是否需要日期)  digit(长度)
     * @return
     */
    public String getSerialNumberByPrefix(String headText, Boolean isYear, Boolean isMonth, Boolean isDay, int digit){

        // 构建 Redis 键
        StringBuilder keyBuilder = new StringBuilder(headText);

        if (isYear) {
            keyBuilder.append(new SimpleDateFormat("yyyy").format(new Date()));
        }

        if (isMonth) {
            keyBuilder.append(new SimpleDateFormat("MM").format(new Date()));
        }

        if (isDay) {
            keyBuilder.append(new SimpleDateFormat("dd").format(new Date()));
        }

        String redisKey = keyBuilder.toString();

        long serialNumber = this.redisTemplate.opsForValue().increment(redisKey, 1);

        // 格式化流水号
        String formattedSerialNumber = String.format("%0" + digit + "d", serialNumber);

        return redisKey + formattedSerialNumber;
    }

    public long incr(String redisKey) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(redisKey, this.redisTemplate.getConnectionFactory());
        return redisAtomicLong.getAndIncrement();
    }

    public static String getSequence(long seq,int length) {
        StringBuilder sb = new StringBuilder();
        //获取年份
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        sb.append(year);
        String str = String.valueOf(seq);
        int len = str.length();
        if (len >= length) {
            return  sb.append(str).toString();
        }
        int rest = length - len;

        for (int i = 0; i < rest; i++) {
            sb.append('0');
        }
        sb.append(str);
        return sb.toString();
    }
}
