package com.ruoyi.oa.service.impl;

import com.ruoyi.oa.mapper.PrefixCounterMapper;
import com.ruoyi.oa.service.CodeGeneratorService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class CodeGeneratorServiceImpl implements CodeGeneratorService {

    @Autowired
    private PrefixCounterMapper mapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String nextCode(String prefix) {
        mapper.upsertAndIncr(prefix);   // 原子插/更
        long num = mapper.getLastSeq(); // 拿到新的序号
        // 改动在这里：%07d 表示数字宽度 7，不足的前面补 0
        String padded = String.format("%07d", num);
        return prefix + "-" + padded;   // e.g. TH-0000001
    }
}
