package digital.laboratory.platform.entrustment.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.common.core.constant.CommonConstants;
import digital.laboratory.platform.entrustment.entity.Identification;
import digital.laboratory.platform.entrustment.handler.AppStartupRunner;
import digital.laboratory.platform.entrustment.mapper.EntrustmentMapper;
import digital.laboratory.platform.entrustment.mapper.IdentificationMapper;
import digital.laboratory.platform.entrustment.service.IdentificationService;
import digital.laboratory.platform.entrustment.vo.IdentificationVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 鉴定表,一个鉴定可能会有多个委托服务实现类
 *
 * @author Zhang Xiaolong created at  2022-07-15
 * @describe 鉴定表,一个鉴定可能会有多个委托 服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class IdentificationServiceImpl extends ServiceImpl<IdentificationMapper, Identification> implements IdentificationService {
	private final IdentificationMapper identificationMapper;

	@Override
	public String getNewIdentificationNo() {
		String year = String.valueOf(DateUtil.year(new Date()));

		String prefix = "JD" + year;
//System.out.printf("year=[%s]", year);

		int newCount = 1;
		// 根据前缀查询最大物证编码
		String maxno = identificationMapper.getMaxIdentificationNo(prefix);
		if (maxno != null) {
			String strCount = StrUtil.removePrefix(maxno, prefix);
			try {
				int maxcount = Integer.parseUnsignedInt(strCount);
				newCount = maxcount + 1;
			} catch (NumberFormatException e) {
				// 如果后缀有非数字, 则无视之, 重头编码
				newCount = 1;
			}
		}

		String strFormat = "%0" + AppStartupRunner.getCfg(CommonConstants.CODE_IDENTIFICATION_NO_SEQUENCE_LENGTH) + "d";
		//System.out.printf("新的 prefix=[%s] newcount=[%s]", prefix, String.format(strFormat, newCount));
		String newCode = prefix + String.format(strFormat, newCount);

		return newCode;
	}

	/**
	 * 根据 caseId 取 IdentificationVO 列表, 每个 Entrustment 一行
	 * @param caseId
	 * @return
	 */
	@Override
	public List<IdentificationVO> getIdentificationVOList(String caseId) {
		return baseMapper.getIdentificationVOList(caseId);
	}

	/**
	 * 根据 caseId 取 Identification 列表, 供新建的补充委托选择老的 Identification(鉴定), 以使新建的委托作为老的鉴定的一部分
	 * @param caseId
	 * @return
	 */
	@Override
	public List<Identification> getIdentificationListByCaseId(String caseId) {
		return baseMapper.getIdentificationListByCaseId(caseId);
	}

}
