package com.artfess.redis.util;

import com.artfess.base.enums.CodePrefix;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * redis编码生成
 *
 * @Author min.wu
 * @Date Created in 2021-09-07
 */
@Component
public class CodeCreatorUtil {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取code（一直叠加）
     *
     * @param key
     * @param prefix
     * @param length
     * @return
     */
    private String createCode(String key, String prefix, int length) {
        if (StringUtils.isEmpty(key) || length < 1) {
            return null;
        }

        //自增数字
        Long lon = redisUtil.incr(key, 1L);
        StringBuilder sb = new StringBuilder(prefix);

        //剩余长度位数
        int sy = length - sb.length() - String.valueOf(lon).length();
        //如果是需要补长度
        if (sy > 0) {
            for (int i = 0; i < sy; i++) {
                sb.append("0");
            }
        }
        sb.append(lon);
        //返回生成的编号
        return sb.toString();
    }


    /**
     * 获取code
     *
     * @param key
     * @param prefix
     * @param length
     * @param format
     * @return
     */
    private String createCode(String key, String prefix, int length, String format) {

        if (StringUtils.isEmpty(key) || length < 1) {
            return null;
        }

        //自增数字
        Long lon = redisUtil.incr(key, 1L);
        StringBuilder sb = new StringBuilder(prefix);

        //拼接日期
        if (!StringUtils.isEmpty(format)) {
            Date now = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            String fmt = simpleDateFormat.format(now);
            sb.append(fmt);
        }

        //剩余长度位数
        int sy = length - sb.length() - String.valueOf(lon).length();
        //如果是需要补长度
        if (sy > 0) {
            for (int i = 0; i < sy; i++) {
                sb.append("0");
            }
        }
        sb.append(lon);
        //返回生成的编号
        return sb.toString();
    }


    /**
     * 获取编码
     *
     * @param codePrefix
     * @param sequenceLength
     * @return
     */
    public String createCode(CodePrefix codePrefix, int sequenceLength) {
        return createCode(codePrefix.getKey(), codePrefix.getPrefix(), sequenceLength);
    }

    /**
     * 获取编码每日更新
     * @return
     */
    public String createCodeYYYYMMDD(CodePrefix codePrefix, int sequenceLength) {
        return createCode(codePrefix.getKey(), codePrefix.getPrefix(), sequenceLength,"yyyyMMdd");
    }

}
