package com.xhpc.common.data.redis;

import cn.hutool.core.date.DateUtil;
import com.xhpc.common.api.PileOrderService;
import com.xhpc.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class StaticBeanUtil {

    public static RedisService REDIS;
    public static PileOrderService ORDER_SVC;

    @Autowired
    public PileOrderService pileOrderService;

    @Autowired
    public RedisService redisService;

    @PostConstruct
    public void init() {

        ORDER_SVC = pileOrderService;
        REDIS = redisService;
    }

    public static Boolean tryLock(String key, long expr) {

        System.out.println("try lock...");
        RedisAtomicInteger counter = new RedisAtomicInteger(key, REDIS.redisTemplate.getConnectionFactory());
        counter.expire(expr, TimeUnit.SECONDS);
        long result = counter.incrementAndGet();
        return result == 1;
    }

    public static Boolean releaseLock(String key) {

        return REDIS.deleteObject(key);
    }

    public synchronized static String seqHex(String key) {

        String upperCode = "";
        RedisAtomicLong counter = new RedisAtomicLong(key, REDIS.redisTemplate.getConnectionFactory());
        long result = counter.incrementAndGet();
        upperCode = String.format("%04X", result);
        if (upperCode.equals("FFFF")) {
            REDIS.deleteObject(key);
        }
        return upperCode;
    }

    public synchronized static String seqDec(String key) {

        String upperCode = "";
        RedisAtomicLong counter = new RedisAtomicLong(key, REDIS.redisTemplate.getConnectionFactory());
        long result = counter.incrementAndGet();
        upperCode = String.format("%04d", result);
        if (upperCode.equals("9999")) {
            REDIS.deleteObject(key);
        }
        return upperCode;
    }

    public synchronized static String seq18Dec(String key) {

        String upperCode = "";
        RedisAtomicLong counter = new RedisAtomicLong(key, REDIS.redisTemplate.getConnectionFactory());
        long result = counter.incrementAndGet();
        upperCode = String.format("%018d", result);
        return upperCode;
    }

    public static String genOrder(String terminalSerialNumber) {

        Date date = Calendar.getInstance().getTime();
        String format = DateUtil.format(date, "yyMMddHHmmss");
        //自增
        String orderNo = terminalSerialNumber + format + seqDec("gun:" + terminalSerialNumber + ".seqdec");
        return orderNo;
    }

}
