package org.jeecg.modules.sequence.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.sequence.entity.MiddleSequence;
import org.jeecg.modules.sequence.mapper.MiddleSequenceMapper;
import org.jeecg.modules.sequence.service.IMiddleSequenceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: middle_attachment
 * @Author: jeecg-boot
 * @Date: 2024-04-26
 * @Version: V1.0
 */
@Slf4j
@Service
public class MiddleSequenceServiceImpl extends ServiceImpl<MiddleSequenceMapper, MiddleSequence> implements IMiddleSequenceService {

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public String generate(String prefix, Integer length) {
        synchronized (Thread.currentThread()) {
            QueryWrapper<MiddleSequence> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(MiddleSequence::getPrefix, prefix);
            MiddleSequence middleSequence = baseMapper.selectOne(queryWrapper);

            int seqCode = 1;
            if (ObjectUtil.isEmpty(middleSequence)) {
                middleSequence = new MiddleSequence();
                middleSequence.setId(IdWorker.getIdStr());
                middleSequence.setPrefix(prefix);
                middleSequence.setSeqCode(seqCode);
                baseMapper.insert(middleSequence);
            } else {
                seqCode = middleSequence.getSeqCode() + 1;
                middleSequence.setSeqCode(seqCode);
                baseMapper.updateById(middleSequence);
            }

            String sequence = prefix + StrUtil.fill(String.valueOf(seqCode), '0', length, true);
            log.info(">>>> 生成序列号参数[{}]，结果[{}]", prefix, sequence);
            return sequence;
        }
    }

}
