package com.changfa.utils;

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

import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class GenerateOrderUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    private final static String KEY_PREFIX = "work:";

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    /**
     * 生成订单号
     */
    public String generateOrder(){
        StringBuilder sb = new StringBuilder();

        //从redis里面取值
        String key = sdf.format(new Date());
        //拼接redis的key
        Long increment = incr(KEY_PREFIX.concat(key),1);
        sb.append(key);

        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }


    /***
     * 按delta递增
     * @param key
     * @param delta
     * @return
     */
    public Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }
}
