package com.zhiqiyun.open.core.service.impl;

import com.zhiqiyun.open.core.mapper.SequenceMapper;
import com.zhiqiyun.open.core.models.Sequence;
import com.zhiqiyun.open.core.service.SequenceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

@Slf4j
@Service
public class SequenceServiceImpl implements SequenceService {

    @Autowired
    private SequenceMapper sequenceMapper;

    private final Random random = new Random();

    @Override
    public Long nextId() {
        Sequence sequence = new Sequence();
        Integer saltRandom = random.nextInt(9);
        sequence.setSaltRandom(saltRandom);
        sequence.setCreatedTime(new Date());
        this.sequenceMapper.insert(sequence);
        String idString = String.format("%s%05d%s", DateFormatUtils.format(sequence.getCreatedTime(), "yyMMdd"), sequence.getId(), saltRandom);
        return Long.valueOf(idString);
    }
}
