package cn.lihu.jh.module.ecg.service.queuesequence; import cn.lihu.jh.module.ecg.Utils; import cn.lihu.jh.module.ecg.dal.dataobject.checktype.CheckTypeDO; import cn.lihu.jh.module.ecg.dal.dataobject.queuesequence.SeqCounterDO; import cn.lihu.jh.module.ecg.dal.mysql.checktype.CheckTypeMapper; import cn.lihu.jh.module.ecg.enums.SeqRuleEnum; import cn.lihu.jh.module.infra.api.config.ConfigApi; import cn.lihu.jh.module.system.api.dict.DictDataApi; import cn.lihu.jh.module.system.api.dict.dto.DictDataRespDTO; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; import java.time.LocalTime; import java.util.*; import cn.lihu.jh.module.ecg.controller.admin.queuesequence.vo.*; import cn.lihu.jh.module.ecg.dal.dataobject.queuesequence.QueueSequenceDO; import cn.lihu.jh.framework.common.pojo.PageResult; import cn.lihu.jh.framework.common.pojo.PageParam; import cn.lihu.jh.framework.common.util.object.BeanUtils; import cn.lihu.jh.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.lihu.jh.module.ecg.dal.mysql.queuesequence.QueueSequenceMapper; import javax.annotation.Resource; import static cn.lihu.jh.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.lihu.jh.module.ecg.Constants.*; import static cn.lihu.jh.module.ecg.enums.ErrorCodeConstants.*; /** * 当天序号 Service 实现类 * * @author 金华医院 */ @Service @Validated @Slf4j public class QueueSequenceServiceImpl implements QueueSequenceService { /** * 向后查找可用时段的最大步数(约 3 小时)。 *
* 取 6 的原因:字典时段为 30 分钟粒度,6 个约 3 小时; * 既能跨过"少数时段缺失/已满"的情况,又不会把上午的患者排到下午造成体验问题。 */ private static final int MAX_TIMESLOT_LOOKAHEAD = 6; @Resource private ConfigApi configApi; @Resource private DictDataApi dictDataApi; @Resource private QueueSequenceMapper queueSequenceMapper; @Resource private CheckTypeMapper checkTypeMapper; /** * 用于把「计数器推进 + 读回」显式包进**同一个事务**。 * *
校验「同一检查类型 + 同一时段」不重复 —— 表上没有该唯一约束(历史遗留), * 而取号 SQL {@code select queue_no ... where check_type=? and time_slot=? for update} * 期望只命中一行;一旦出现重复行,取号会命中不确定的一行。 * 这里在维护入口处拦截,给出明确提示而不是让问题进入取号阶段。 */ @Override public Integer createQueueSequence(QueueSequenceSaveReqVO createReqVO) { validateTimeslotNotDuplicated(createReqVO.getCheckType(), createReqVO.getTimeSlot(), null); // 插入 QueueSequenceDO queueSequence = BeanUtils.toBean(createReqVO, QueueSequenceDO.class); if (null == queueSequence.getTimeSlot() || 0 != queueSequence.getTimeSlot()) { // 【本需求】号段起点 / 预留起点由系统计算,不接受前端随意传值(否则号段会重叠) queueSequence.setQueueSet(null); queueSequence.setQueueVipSet(null); } queueSequenceMapper.insert(queueSequence); // 【本需求】新增/编辑后统一重排该检查类型的号段(保证"段与段首尾相接") if (null != createReqVO.getCheckType()) { recalcSegmentBounds(createReqVO.getCheckType()); } // 返回 return queueSequence.getId(); } @Override public void updateQueueSequence(QueueSequenceSaveReqVO updateReqVO) { // 校验存在 validateQueueSequenceExists(updateReqVO.getId()); // 【校验】改了 checkType 或 timeSlot 时不能与其它行撞车(排除自身) validateTimeslotNotDuplicated(updateReqVO.getCheckType(), updateReqVO.getTimeSlot(), updateReqVO.getId()); // 更新 QueueSequenceDO updateObj = BeanUtils.toBean(updateReqVO, QueueSequenceDO.class); // 【本需求】起始序号由系统重排,忽略前端传值(前端已置为只读) updateObj.setQueueSet(null); updateObj.setQueueVipSet(null); queueSequenceMapper.updateById(updateObj); if (null != updateReqVO.getCheckType()) { recalcSegmentBounds(updateReqVO.getCheckType()); } } /** * 【本需求】按「时段升序」重排某检查类型的号段: *
* 段 i:queue_set = 上一段的 queue_vip_full(首段 0)
* queue_full = queue_set + P
* queue_vip_set = queue_full
* queue_vip_full = queue_vip_set + V
* 其中 P / V = 该行当前的(queue_full - queue_set)、(queue_vip_full - queue_full),
* 即各段的"额度"保持不变,只把起点串起来。
*
* 这样无论新增/删除/编辑时段,都不会出现号段重叠或空洞错位。
* 总预留池(time_slot = 0)不参与重排,只把起点对齐到最后一段之后。
*/
private void recalcSegmentBounds(Integer checkType) {
if (null == checkType) {
return;
}
List
* 与普通通道的差别只在于"跳过本段普通号",其余(预留号、总池兜底)完全一致。
*/
@Override
@Transactional
public Integer distributeVipSeqNo(Integer checkType, Integer timeslot) {
Integer curVipSeqNo = queueSequenceMapper.selectQueueVipNoForUpdate(checkType, timeslot);
if (null != curVipSeqNo) {
Integer updateRowNum = queueSequenceMapper.updateGivenCheckTypeTimeslotVipSeqNo(checkType, timeslot, curVipSeqNo);
if (null != updateRowNum && updateRowNum > 0) {
return curVipSeqNo + 1;
}
log.info("[distributeVipSeqNo] 本段预留号并发被抢空,降级到总预留池. checkType={} timeslot={}", checkType, timeslot);
}
return nextTotalPoolSeqNo(checkType, timeslot);
}
/**
* 【本需求】总预留池取号({@code time_slot = 0} 那一行)—— **永不失败**。
*
*
* 与四参版本的唯一差别:按时段预约(TIMESLOT)下,VIP/加号患者**直接取本段预留号**
* (见 {@link #distributeVipSeqNo}),而不是先取普通号;签到序号(CHECKIN)下
* VIP/加号同样可占用预留号(每 9 留 1 的预留位)。
*/
@Override
@Transactional
public Integer distributeSeqNoByRule(Integer checkType, Integer timeslot,
Integer existingSeqNo, boolean urgent, boolean vip) {
SeqRuleEnum rule = resolveRule(checkType);
switch (rule) {
case APPOINT:
// ① 预约号:预约系统已给号则直接用;否则回退到签到序号(避免患者拿不到号)
if (null != existingSeqNo && existingSeqNo > 0) {
log.info("[distributeSeqNoByRule] 规则=预约号,直接使用预约系统号. checkType={} seqNo={}",
checkType, existingSeqNo);
return existingSeqNo;
}
log.warn("[distributeSeqNoByRule] 规则=预约号,但预约系统未下发号,回退到签到序号. checkType={}",
checkType);
return nextCheckInSeqNo(checkType, urgent || vip);
case CHECKIN:
// ② 签到序号:当天同检查类型连续递增,每 9 个预留 1 个
return nextCheckInSeqNo(checkType, urgent || vip);
case TIMESLOT:
default:
// ③ 时段号:VIP/加号走「本段预留号 → 总预留池」;普通走「普通 → 预留 → 总池」
if (vip) {
return distributeVipSeqNo(checkType, timeslot);
}
return distributeSeqNo(checkType, timeslot);
}
}
/**
* 解析某检查类型配置的排队序号规则;查不到配置或未配置时返回默认(时段号)。
*/
private SeqRuleEnum resolveRule(Integer checkType) {
if (null == checkType) {
return SeqRuleEnum.DEFAULT;
}
CheckTypeDO checkTypeDO = checkTypeMapper.getCheckTypeByValue(checkType);
if (null == checkTypeDO) {
log.warn("[resolveRule] 未找到检查类型配置,使用默认规则(时段号). checkType={}", checkType);
return SeqRuleEnum.DEFAULT;
}
return SeqRuleEnum.parse(checkTypeDO.getSeqRule());
}
/**
* 计算下一个「签到序号」。
*
*
* 与旧的 {@code getNextTimeSlot} 的区别:
* 为什么不会满
* 总池的 {@code queue_vip_full} 在发号时同步"顶高"(见 Mapper 的
* {@code advanceTotalPoolVipNo}),因此 {@code queue_vip_no} 永远可以继续 +1。
* 这是"绝不出现签不上"的最后一道兜底。
*
* 总池行缺失时自动补
* 号段放在当天所有时段的最大号之后({@code max(queue_vip_full)}),
* 保证总池号 **大于所有时段号** ⇒ 排序天然排在全天最后。
*/
private Integer nextTotalPoolSeqNo(Integer checkType, Integer timeslot) {
Integer curVipNo = null;
try {
curVipNo = queueSequenceMapper.selectTotalPoolVipNo(checkType);
} catch (Exception e) {
log.warn("[nextTotalPoolSeqNo] 读取总预留池异常,按缺失处理. checkType={}", checkType, e);
}
if (null == curVipNo) {
// 现场兜底:自动补一行总预留池(幂等:以 检查类型 + time_slot=0 唯一)
Integer base = queueSequenceMapper.selectMaxVipFullOfCheckType(checkType);
if (null == base) {
base = 0;
}
QueueSequenceDO pool = new QueueSequenceDO();
pool.setCheckType(checkType);
pool.setTimeSlot(0);
pool.setQueueSet(0);
pool.setQueueNo(0);
pool.setQueueFull(0);
pool.setQueueVipSet(base);
pool.setQueueVipNo(base);
pool.setQueueVipFull(base);
try {
queueSequenceMapper.insert(pool);
} catch (Exception e) {
// 并发下可能已被别的线程插入,忽略后继续读
log.warn("[nextTotalPoolSeqNo] 补总预留池行失败(可能并发已插入),继续取号. checkType={}", checkType, e);
}
if (null == queueSequenceMapper.selectTotalPoolVipNo(checkType)) {
// 插入后仍读不到(极端情况)→ 用当天最大号兜底,保证能签到
Integer maxFull = queueSequenceMapper.selectMaxVipFullOfCheckType(checkType);
log.error("[nextTotalPoolSeqNo] 总预留池不可用,使用最大号兜底. checkType={} maxFull={}", checkType, maxFull);
return (null == maxFull ? 0 : maxFull) + 1;
}
}
Integer updateNum = queueSequenceMapper.advanceTotalPoolVipNo(checkType);
if (null == updateNum || updateNum == 0) {
throw exception(QUEUE_SEQUENCE_TIMESLOT_EXCEPTION);
}
Integer after = queueSequenceMapper.selectTotalPoolVipNo(checkType);
if (null == after) {
throw exception(QUEUE_SEQUENCE_TIMESLOT_EXCEPTION);
}
log.info("[nextTotalPoolSeqNo] 已从总预留池取号(本段已满或没有时段). checkType={} timeslot={} seqNo={}",
checkType, timeslot, after);
return after;
}
/**
* 按【检查类型配置的规则】分配排队序号。
*
* 三种规则
*
*
*
* 为什么规则 1 需要独立计数器
* 不能用 {@code MAX(book_seq_num)+1} 计算:预留号(10、20…)若无人使用就不会出现在
* 数据里,下一个普通号按 MAX+1 会再次算出同一个预留号,造成冲突。
* 因此用 {@code seq_counter} 表**必须被消耗**地递增(见 Mapper 的 LAST_INSERT_ID 写法)。
*/
@Override
@Transactional
public Integer distributeSeqNoByRule(Integer checkType, Integer timeslot,
Integer existingSeqNo, boolean urgent) {
// 兼容旧调用方:未传 VIP 标记时按"非 VIP"处理
return distributeSeqNoByRule(checkType, timeslot, existingSeqNo, urgent, false);
}
/**
* 【本需求】带 VIP/加号标记的取号入口。
* 两个独立计数器(这是踩坑后的结论)
* {@code seq_counter} 维护两个互不干扰的计数器:
*
*
* 为什么不能只用一个计数器:若用单个 {@code candidate} 递增后再"跳过预留号",
* 必然撞车 —— 普通患者拿到 candidate=10 → 跳过得 11;下一个普通患者拿到 candidate=11
* → 也得 11。实测 20 次取号中第 10、11 次分配号相同。
* 两个计数器物理隔离后,二者取值域不相交,**不可能重号**。
*
* 并发(两处坑,均已修复)
*
*
* 实测 8 线程 × 20 次 = 160 次取号:同事务 160/160 唯一、号值连续;
* 独立事务只有 75/160 —— 详见 Mapper 注释。
*/
private Integer nextCheckInSeqNo(Integer checkType, boolean urgent) {
final LocalDate today = LocalDate.now();
// 用显式事务把「推进」与「读回」包在一起(@Transactional 在此处不生效,见方法注释)
Integer assigned = counterTransactionTemplate.execute(status -> {
if (urgent) {
queueSequenceMapper.advanceReservedSeq(checkType, today);
} else {
queueSequenceMapper.advanceNormalSeq(checkType, today);
}
SeqCounterDO counter = queueSequenceMapper.getSeqCounter(checkType, today);
if (null == counter) {
return null;
}
return urgent ? counter.getReservedNext() : counter.getNormalNext();
});
if (null == assigned) {
// 理论上不会发生(刚推进过);保守回退,避免抛错阻断签到
assigned = urgent ? SeqRuleEnum.ROUND_SIZE : 1;
log.error("[nextCheckInSeqNo] 计数器读取失败,回退为默认号. checkType={} 加急={} 回退号={}",
checkType, urgent, assigned);
}
log.info("[nextCheckInSeqNo] 规则=签到序号. checkType={} 加急={} 本次分配={}",
checkType, urgent, assigned);
return assigned;
}
/**
* 向后查找一个**仍有余量**的预约时段。
*
*
*
* @param checkType 检查类型
* @param timeslot HIS 传入的预约时段(可能是字典外的 60 分钟粒度值)
* @param includeVip true 时要求 VIP 号也有余量
* @return 可用的时段值;无可用时段返回 null
*/
private Integer findAvailableTimeslot(Integer checkType, Integer timeslot, boolean includeVip) {
List