package com.aucma.common.utils.uuid;

import com.aucma.common.core.redis.RedisCache;
import com.aucma.common.utils.StringUtils;
import com.aucma.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName : PlanCodeUtils
 * @Description : zhouhy
 * @Author :生产计划-计划编号生成
 * @Date: 2023-10-07 09:46
 */
@Component
public class PlanCodeUtils {


    public static String getPlanCode() {
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
        String format = "plan_code:" + date.format(formatter);
        //以当日日期作为key
        if (!SpringUtils.getBean(RedisCache.class).hasKey(format)) {
            SpringUtils.getBean(RedisCache.class).setCacheObject(format, 1);
            SpringUtils.getBean(RedisCache.class).expire(format, getSecondsNextEarlyMorning(), TimeUnit.SECONDS);
        } else {
            //获取当前的value在+1
            Object cacheObject = SpringUtils.getBean(RedisCache.class).getCacheObject(format);
            String value = String.valueOf(cacheObject);
            Integer integer = Integer.parseInt(value) + 1;
            SpringUtils.getBean(RedisCache.class).setCacheObject(format, integer);
            SpringUtils.getBean(RedisCache.class).expire(format, getSecondsNextEarlyMorning(), TimeUnit.SECONDS);
        }
        Object cacheObject = SpringUtils.getBean(RedisCache.class).getCacheObject(format);
        //转成string在转成int
        String code = String.format("%04d", Integer.valueOf(String.valueOf(cacheObject)));

        return date.format(formatter) + code;
    }

    //判断当前时间距离第二天0点时间的秒数
    public static Long getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }


}
