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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.database.entity.ExperimentSequence;
import org.jeecg.modules.database.mapper.ExperimentSequenceMapper;
import org.jeecg.modules.database.service.IExperimentSequenceService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description: 试验序列
 * @Author: jeecg-boot
 * @Date: 2024-12-04
 * @Version: V1.0
 */
@Service
public class ExperimentSequenceServiceImpl extends ServiceImpl<ExperimentSequenceMapper, ExperimentSequence>
        implements IExperimentSequenceService {

    @Override
    public String next() {
        LambdaQueryWrapper<ExperimentSequence> queryWrapper = new LambdaQueryWrapper<>();
        int year = DateUtil.year(new Date());
        queryWrapper.eq(ExperimentSequence::getSequenceYear, year);
        queryWrapper.orderByDesc(ExperimentSequence::getSequenceYear);
        queryWrapper.orderByDesc(ExperimentSequence::getSequenceValue);
        queryWrapper.orderByDesc(ExperimentSequence::getCreateTime);
        ExperimentSequence sequence = getOne(queryWrapper, false);
        int sequenceValue = 0;
        if (sequence != null) {
            sequenceValue = sequence.getSequenceValue();
        }
        ExperimentSequence seq = new ExperimentSequence();
        seq.setSequenceYear(year + "");
        seq.setSequenceValue(sequenceValue + 1);
        save(seq);
        return assembleSequence(seq);
    }

    public String assembleSequence(ExperimentSequence experimentSequence) {
        return "KC-" + experimentSequence.getSequenceYear() + "-JL-" + StringUtils.leftPad(experimentSequence.getSequenceValue() + "",
                3, "0");
    }
}
