package com.cftech.base.codingrule.utils;

import com.cftech.base.codingrule.model.Codingrule;
import com.cftech.base.codingrule.service.CodingruleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

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

/**
 * Created by liuling on 2017/2/17.
 */
@Component
public class CodingruleUtils {

    private final CodingruleService codingruleService;

    private final RedisTemplate<String, String> redisTemplate;

    private RedisTemplate<String, String> getConfig() {
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
//        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        return redisTemplate;
    }

    @Autowired
    public CodingruleUtils(CodingruleService codingruleService, RedisTemplate<String, String> redisTemplate) {
        this.codingruleService = codingruleService;
        this.redisTemplate = redisTemplate;
    }


    public String getNumber(Long accountsId, String clzName) {
        Codingrule codingrule = codingruleService.findByAccountsIdAndBo(accountsId, clzName);
        if (codingrule == null) {
            return "";
        }
        //编码模版
        String tpl = codingrule.getTpl();
        String dateformatStr = "yyyyMMdd";
        SimpleDateFormat sdf = new SimpleDateFormat(dateformatStr);
        String today = sdf.format(new Date());
        //昨天的时间
        String lastDate = sdf.format(new Date(new Date().getTime() - 24 * 60 * 60 * 1000));
        String key = accountsId + "-" + clzName;
        String lastkey = accountsId + "-" + clzName + "-" + lastDate;
        if(tpl.indexOf(dateformatStr) != -1){
            key+="-" + today;;
            //如果模版包含日期，则删除昨日的key值
            if (getConfig().hasKey(lastkey)) {
                getConfig().delete(lastkey);
            }
            tpl = tpl.replace("yyyyMMdd", today);
        }
        //每次自增1，无过期时间
        long count = getConfig().opsForValue().increment(key, 1);
        String number = String.valueOf(count);
        tpl = tpl.replaceAll("[*]", "0");
        tpl = tpl.substring(0, tpl.length() - number.length()) + number;
        return tpl;
    }
}
