package com.xinelu.common.utils.codes;


import com.xinelu.common.utils.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.concurrent.TimeUnit;

/**
 * @Description 编号工具类
 * @Author 纪寒
 * @Date 2022-08-02 18:13:55
 * @Version 1.0
 */
@Component
public class GenerateSystemCodeUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 使用Redis生成唯一不重复的编码
     *
     * @param prefixCode 编号前缀
     * @return 编号信息 MMdd
     */
    public String generatePatientCode(String prefixCode) {
        DecimalFormat df = new DecimalFormat("0000");
        String dateFmt = DateUtils.formatDateToString(LocalDate.now(), "MMdd");
        Long maxVal = redisTemplate.opsForValue().increment(prefixCode, 1);
        //redis有效期开始时间
        LocalDateTime now = LocalDateTime.now();
        //redis有效期结束时间
        LocalDateTime end = DateUtils.end(LocalDate.now());
        redisTemplate.expire(prefixCode, DateUtils.differenceMinutes(now, end), TimeUnit.MINUTES);
        return dateFmt + df.format(maxVal);
    }


    /**
     * 使用Redis生成唯一不重复的编码
     *
     * @param prefixCode 编号前缀
     * @return 编号信息 yyyyMMdd
     */
    public String generateSystemCode(String prefixCode) {
        DecimalFormat df = new DecimalFormat("0000");
        String dateFmt = DateUtils.formatDateToString(LocalDate.now(), "yyyyMMdd");
        Long maxVal = redisTemplate.opsForValue().increment(prefixCode, 1);
        //redis有效期开始时间
        LocalDateTime now = LocalDateTime.now();
        //redis有效期结束时间
        LocalDateTime end = DateUtils.end(LocalDate.now());
        redisTemplate.expire(prefixCode, DateUtils.differenceMinutes(now, end), TimeUnit.MINUTES);
        return dateFmt + df.format(maxVal);


    }

    /**
     * 生成科室编码
     *
     * @param prefixCode 科室名称前缀
     * @return 科室编码
     */
    public String generateDepartCode(String prefixCode) {
        DecimalFormat df = new DecimalFormat("00000");
        String dateFmt = DateUtils.formatDateToString(LocalDate.now(), "yyyy");
        Long maxVal = redisTemplate.opsForValue().increment(prefixCode, 1);
        //redis有效期开始时间
        LocalDateTime now = LocalDateTime.now();
        //redis有效期结束时间
        LocalDateTime end = DateUtils.end(LocalDate.now().plusYears(0).with(TemporalAdjusters.lastDayOfYear()));
        redisTemplate.expire(prefixCode, DateUtils.differenceMinutes(now, end), TimeUnit.MINUTES);
        return dateFmt + df.format(maxVal);
    }
}
