package com.hxhq.business.service.impl;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
        import com.hxhq.common.core.utils.DateUtils;
import com.hxhq.common.core.utils.SpringUtils;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.SnGenMapper;
import com.hxhq.business.domain.SnGen;
import com.hxhq.business.service.ISnGenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 每日编号生成记录Service业务层处理
 *
 * @author hxhq
 * @date 2026-01-12
 */
@Service
public class SnGenServiceImpl extends ServiceImpl<SnGenMapper, SnGen> implements ISnGenService
{
    /**
     * true表示公平锁
     */
    private final Lock lock = new ReentrantLock(true);

    @Override
    public String getNewSn(Integer type, String my) {
        lock.lock();
        try {
            Integer sort = 1;
            String date = StringUtils.isBlank(my)? DateUtils.dateTimeNow("yyMMdd"):my;
            QueryWrapper<SnGen> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("date",date);
            queryWrapper.eq("type",type);
            if(count(queryWrapper)==0){
                SnGen snGen = new SnGen();
                snGen.setDate(date);
                snGen.setSn(sort);
                snGen.setType(type);
                save(snGen);
            }else{
                baseMapper.addSn(date,type);
                sort = getOne(queryWrapper,false).getSn();
            }
            return (StringUtils.isBlank(my)?(date+"-"):"")+String.format("%03d", sort);
        } catch (Exception e) {
            log.error("getNewSn执行被中断", e);
        } finally {
            lock.unlock();
        }
        return null;
    }

    @Override
    public String getNewSn(Integer type) {
        return getNewSn(type,null);
    }
}
