package com.qmth.distributed.print.business.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.distributed.print.business.service.BasicExamService;
import com.qmth.teachcloud.common.entity.BasicExam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生成编码、准考证号等工具类
 */
@Component
public class CodeUtils {

    Lock lock = new ReentrantLock();

    @Resource
    BasicExamService basicExamService;

    /**
     * 生成考试简码
     *
     * @param schoolId 学校ID
     */
    public String createBasicExamShortCode(Long schoolId) {
        try {
            lock.lock();
            QueryWrapper<BasicExam> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(BasicExam::getSchoolId, schoolId);
            List<BasicExam> basicExams = basicExamService.list(queryWrapper);
            if (basicExams.isEmpty()) {
                return "001";
            } else {
                Optional<BasicExam> max = basicExams.stream().filter(m -> StringUtils.isNotBlank(m.getShortCode())).max(Comparator.comparing(BasicExam::getShortCode));
                if (!max.isPresent()) {
                    return "001";
                }
                String maxShortCode = max.get().getShortCode();
                int shortCode = StringUtils.isBlank(maxShortCode) ? 0 : Integer.parseInt(maxShortCode);
                return String.format("%03d", shortCode + 1);
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException("生成考试编码失败");
        } finally {
            lock.unlock();
        }
    }
}
