package com.yd.csf.service.component;

import com.yd.common.exception.BusinessException;
import com.yd.csf.service.dto.CommissionExpectedAddDto;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Component
public class ReceivableService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    // Redis key前缀
    private static final String ADDITIONAL_NO_PREFIX = "receivable:additional:";

    // 日期格式
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    public String generateReceivableNo(String commissionBizType, String reconciliationCompanyCode, String reconciliationCompany) {
        CommissionExpectedAddDto commissionExpectedAddDto = new CommissionExpectedAddDto();
        commissionExpectedAddDto.setCommissionBizType(commissionBizType);
        commissionExpectedAddDto.setReconciliationCompanyCode(reconciliationCompanyCode);
        commissionExpectedAddDto.setReconciliationCompany(reconciliationCompany);
        return generateAdditionalReceivableNo(commissionExpectedAddDto);
    }

    private String generateAdditionalReceivableNo(CommissionExpectedAddDto addDto) {
        String reconciliationCompanyCode = addDto.getReconciliationCompanyCode();
        if (ObjectUtils.isEmpty(reconciliationCompanyCode)) {
            throw new BusinessException("对账公司编码不能为空");
        }
        LocalDate today = LocalDate.now();
        String dateStr = today.format(DATE_FORMATTER);

        // 获取当天流水号（从1开始）
        long dailySeq = getDailySequence();

        // 格式：应收款类型-对账公司代码-年份后两位-席号(6位数字)
        return String.format("%s%s%s%06d",
                "R".equals(addDto.getCommissionBizType()) ? "R-" : "U-",
                reconciliationCompanyCode,
                dateStr.substring(2, 4), // 取年份后两位
                dailySeq);
    }

    private long getDailySequence() {
        LocalDate today = LocalDate.now();
        String redisKey = ADDITIONAL_NO_PREFIX + today.format(DATE_FORMATTER);

        ValueOperations<String, String> ops = redisTemplate.opsForValue();

        // 使用Redis的INCR命令获取自增序列
        Long seq = ops.increment(redisKey, 1);

        // 如果是第一次设置（值为1），设置过期时间为1天+2小时（避免跨天问题）
        if (seq != null && seq == 1L) {
            redisTemplate.expire(redisKey, 26, TimeUnit.HOURS); // 26小时，确保覆盖全天
        }

        return seq;
    }
}