package com.chinaweal.aiccs.common.util;


import com.chinaweal.aiccs.aiccs.punishment.service.TridmakerService;
import com.chinaweal.aiccs.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Component
public class UuidUtil {

    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private RedisService redisService;

    public static String getUuid() {
        return UUID.randomUUID().toString();
    }

    private String getTridmaker(String makerID) {
        String num = null;
        Integer curnum = -1;
        Integer nextNum = -1;

        //获取当前的时间格式 2013-06-04
        Calendar curCl = Calendar.getInstance();
        Map<String, Object> makerMap;
        try {
            makerMap = jdbcTemplate.queryForMap("select * from Tridmaker where makerID = ?", makerID);
            //比较当前时间和数据库存储的时间
            Calendar dataCl = Calendar.getInstance();
            Date _curDate = (Date) makerMap.get("curDate");
            if (_curDate != null) {
                dataCl.setTime(_curDate);
            }
            if(curCl.get(Calendar.YEAR) == dataCl.get(Calendar.YEAR)){
                curnum = (Integer) makerMap.get("curnum");
            } else {
                curnum = 0;
                makerMap.put("curDate", new Date(curCl.getTime().getTime()));
            }
            nextNum = curnum + 1;
            makerMap.put("curnum", nextNum);
            jdbcTemplate.update("update Tridmaker set curnum = ?, curDate = ? where makerID = ?", makerMap.get("curnum"), makerMap.get("curDate"), makerMap.get("makerID"));
        } catch (EmptyResultDataAccessException e) {
            log.info("不存在传入的注册号生成规则，现按照acceptNo规则生成。");
            curnum = 0;
            nextNum = curnum + 1;
            makerMap = new HashMap<String, Object>();
            makerMap.put("makerID", makerID);
            makerMap.put("curnum", nextNum);
            makerMap.put("curDate", curCl.getTime());
            jdbcTemplate.update("insert Tridmaker(makerID, curnum, curDate) values(?, ?, ?)", makerMap.get("makerID"), makerMap.get("curnum"), makerMap.get("curDate"));
        }

        //根据规则生成受理号
        int year = curCl.get(Calendar.YEAR);
        num = "7" + String.valueOf(year).substring(2, 4) + beforeZeroFill(nextNum, 8);
        return num;
    }


    /**
     * 规则年月日+5位顺序号。例如：13060400001
     *
     * @return 新产生的流水号
     */
    public synchronized String getCurAcceptNo() {
        return getTridmaker("acceptNoForCase");
    }

    /**
     * 规则年月日+5位顺序号。例如：13060400001
     *
     * @return 新产生的流水号(Redis)  todo: 新的一年要重新获取
     */
//    public String getCurAcceptNo() {
//        String key = "Redis_acceptNoForCase";
//        String num = null;
//        if (redisService.exists(key)) {
//            num = redisService.incr(key);
//
//            // 根据规则生成受理号
//            LocalDate localDate = LocalDate.now();
//            int year = localDate.getYear();
//            return "7" + String.valueOf(year).substring(2, 4) + beforeZeroFill(num, 8);
//        } else {
//            throw new RuntimeException("获取新产生的流水号异常");
//        }
//    }


//    /**
//     * 规则年月日+5位顺序号。例如：13060400001
//     *
//     * @return 新产生的流水号(Redis)  todo: 新的一年要重新获取
//     */
//    public String getCurAcceptNo() {
//        String key = "Redis_acceptNoForCase";
//        String num = null;
//
//        try {
//            // 检查key是否存在，如果不存在则初始化
//            if (!redisService.exists(key)) {
//                // 初始化值为1，设置过期时间（可选，根据业务需求）
//                redisService.set(key, "0");
//                // 可选：设置过期时间，例如24小时
//                // redisService.expire(key, 86400);
//            }
//
//            // 自增并获取值
//            num = redisService.incr(key);
//
//            // 根据规则生成受理号
//            LocalDate localDate = LocalDate.now();
//            int year = localDate.getYear();
//            return "7" + String.valueOf(year).substring(2, 4) + beforeZeroFill(num, 8);
//
//        } catch (Exception e) {
//            // 捕获所有可能的异常（如Redis连接异常等）
//            throw new RuntimeException("获取新产生的流水号异常: " + e.getMessage(), e);
//        }
//    }

    /**
     * 产生缴费通知书流水号。例如：44000000014090100338
     *
     * @param aicID
     * @return
     */
    public synchronized String getFeeNoticeNo(String aicID) {
        return afterZeroFill(aicID, 9) + getTridmaker(aicID + "feenoticenoid");
    }

    /**
     * @param number 需要填充0的数字
     * @param length 需要多少位
     * @return
     */
    private String beforeZeroFill(int number, int length) {
        return beforeZeroFill(String.valueOf(number), length);
    }

    private String beforeZeroFill(String number, int length) {
        String tmp = number;
        for (int i = 0; i < length - number.length(); i++) {
            tmp = "0" + tmp;
        }
        return tmp;
    }

    private String afterZeroFill(String number, int length) {
        StringBuilder tmp = new StringBuilder(number);
        for (int i = 0; i < length - number.length(); i++) {
            tmp.append("0");
        }
        return tmp.toString();
    }
}
