package com.prolog.cs.biz.inbound.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Component
public class SerialGeneratorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public SerialGeneratorService() {
    }

    /**
     * 生成业务流水号 系统标识（sysFlg.length位）+时间（14位，年月日时分秒）+流水号（randomCount位）
     *
     * @param prefix  编码前缀
     * @param length 流水号位数
     * @param serviceId 业务唯一标识
     * @param dateFormat 日期格式
     * @return
     */
    public String getSerialNum(String prefix,Integer length,String serviceId,String dateFormat){
        String fullPrefix = getFullPrefix(prefix,dateFormat);
        Long incrementalSerial = stringRedisTemplate.opsForValue().increment(serviceId+":"+fullPrefix,1);
        String str = String.format("%0"+length+"d", incrementalSerial);
        return fullPrefix +str;
    }

    private String getFullPrefix(String prefix, String dateFormat) {
        StringBuilder serialPrefix = new StringBuilder();
        //前缀
        if(!StringUtils.isEmpty(prefix)){
            serialPrefix.append(prefix);
        }
        //日期
        if(StringUtils.hasText(dateFormat)){
            String s = LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateFormat));
            serialPrefix.append(s);
        }
        return serialPrefix.toString();
    }
}
