package com.zt.plat.module.qms.business.bus.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONFactory;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.qlexpress4.Express4Runner;
import com.alibaba.qlexpress4.QLOptions;
import com.alibaba.qlexpress4.QLResult;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.esotericsoftware.minlog.Log;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.qms.business.bus.controller.vo.*;
import com.zt.plat.module.qms.business.bus.controller.vo.BatchResultDataReportingReqVO.BusinessSubParentSampleIdAndRetestCount;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayParameterDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayProjectDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskDetailDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskParameterDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessQCCoefficientDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessQCManagementDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubParentSampleAssessmentDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubParentSampleAssessmentProjectDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubParentSampleDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleAssessmentDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleAssessmentProjectDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleDO;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayParameterDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayProjectDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayReportDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskDetailMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskParameterDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessBaseSampleMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessQCCoefficientDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessQCCoefficientParameterDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessQCManagementDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessQCManagementParameterDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessQCManagementProjectDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessQCManagementSampleParameterDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubParentSampleAssessmentMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubParentSampleAssessmentProjectMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubParentSampleMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleAssessmentMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleAssessmentProjectMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleMapper;
import com.zt.plat.module.qms.business.config.controller.vo.*;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigAssayMethodParameterDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigAssayMethodProjectAssessmentDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigAssayMethodProjectParameterDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigRuleDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigSubSampleDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigSubSampleParentMethodDO;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodParameterMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodProjectAssessmentMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodProjectCoefficientMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodProjectMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodProjectParameterMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigProjectMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigReportFieldMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigReportTypeMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigRuleMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigSampleReportMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigSubSampleMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigSubSampleMethodMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigSubSampleParentMethodMapper;
import com.zt.plat.module.qms.common.dic.controller.vo.DictionaryBusinessExtendRespVO;
import com.zt.plat.module.qms.common.dic.dal.mapper.DictionaryBusinessMapper;
import com.zt.plat.module.qms.core.qlexpress.cmp.AllowanceCalculatorComponent;
import com.zt.plat.module.qms.core.util.number.EffectiveNumberFormatter;
import com.zt.plat.module.qms.enums.QmsCommonConstant;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import jakarta.annotation.Resource;
import tech.zzjc.tio.utils.cache.caffeine.DefaultRemovalListener;

/**
 * <b>SampleAnalysisAuditServiceImpl</b>
 * <p>
 * 更新历史：
 * <pre> 版本         更新时间            更新者        更新内容<hr/>
 * V1.0      2025年9月29日          wxr         Add</pre>
 * <b>Copyright (C)  云南志者竟成科技有限公司</b> 
 * </p>
 * @author 王兴荣<wxr@wangxingrong.com>
 * @version V1.0 
 * @since 2025年9月29日
 */
@Service
public class SampleAnalysisAuditServiceImpl implements SampleAnalysisAuditService {
	
	@Resource
	private Express4Runner express4Runner;
	
	@Resource
	private AllowanceCalculatorComponent allowanceCalculatorComponent;
	
	@Resource
	private BusinessAssayTaskMapper businessAssayTaskMapper;
	
	@Resource
	private BusinessAssayTaskParameterDataMapper businessAssayTaskParameterDataMapper;
	
	@Resource
	private BusinessAssayTaskDetailMapper businessAssayTaskDetailMapper;
	
	@Resource
	private BusinessAssayTaskDataMapper businessAssayTaskDataMapper;
	
	@Resource
	private BusinessAssayProjectDataMapper businessAssayProjectDataMapper;
	
	@Resource
	private BusinessQCCoefficientDataMapper businessQCCoefficientDataMapper;
	
	@Resource
	private BusinessQCCoefficientParameterDataMapper businessQCCoefficientParameterDataMapper;
	
	@Resource
	private BusinessQCManagementDataMapper businessQCManagementDataMapper;
	
	@Resource
	private BusinessQCManagementSampleParameterDataMapper businessQCManagementSampleParameterDataMapper;
	
	@Resource
	private BusinessQCManagementProjectDataMapper businessQCManagementProjectDataMapper;
	
	@Resource
	private BusinessQCManagementParameterDataMapper businessQCManagementParameterDataMapper;
	
	@Resource
	private ConfigAssayMethodProjectAssessmentMapper configAssayMethodProjectAssessmentMapper;
	
	@Resource
	private BusinessSubSampleAssessmentMapper businessSubSampleAssessmentMapper;
	
	@Resource
	private BusinessSubSampleAssessmentProjectMapper businessSubSampleAssessmentProjectMapper;
	
	@Resource
	private ConfigAssayMethodProjectMapper configAssayMethodProjectMapper;
	
	@Resource
	private ConfigAssayMethodProjectParameterMapper configAssayMethodProjectParameterMapper;
	
	@Resource
	private ConfigAssayMethodProjectCoefficientMapper configAssayMethodProjectCoefficientMapper;
	
	@Resource
	private ConfigSubSampleMethodMapper configSubSampleMethodMapper;
	
	@Resource
	private DictionaryBusinessMapper dictionaryBusinessMapper;

	@Override
	public JSONObject getSampleResultAssessmentList(BusinessAssayTaskDataReqVO reqVO) {
		Long configAssayMethodId = reqVO.getConfigAssayMethodId();
		String asmtReportedStatus = reqVO.getAsmtReportedStatus();
		List<ConfigAssayMethodProjectExtendRespVO> configAssayMethodProjectDOList = configAssayMethodProjectMapper.selectByConfigAssayMethodId(configAssayMethodId);
		List<Map<String, Object>> columnList = new ArrayList<>();

		for (ConfigAssayMethodProjectExtendRespVO configAssayMethodProject : configAssayMethodProjectDOList) {
			columnList.add(new HashMap<String, Object>() {
				private static final long serialVersionUID = 2100402322138923549L;

			{
				put("title", configAssayMethodProject.getShowName() + "(" + configAssayMethodProject.getDictionaryProjectUnit() + ")");
				put("field", configAssayMethodProject.getSimpleName());
				put("dataType", configAssayMethodProject.getDataType());
				put("decimalPosition", configAssayMethodProject.getDecimalPosition());
				put("isEdit", true);
			}});
		}
		
		List<Map<String, Object>> dataList = new ArrayList<>();
		BusinessAssayTaskDataReqVO search = new BusinessAssayTaskDataReqVO();
		search.setConfigAssayMethodId(configAssayMethodId);
		search.setAsmtReportedStatus(asmtReportedStatus);
		search.setSampleReceiveTime(reqVO.getSampleReceiveTime());
		List<BusinessAssayTaskDataExtendRespVO> resultAssessmentList = businessAssayTaskDataMapper.selectResultAssessmentList(search);
		
		for (BusinessAssayTaskDataExtendRespVO businessAssayTaskDataExtendRespVO : resultAssessmentList) {
			Map<String,Object> businessAssayTaskDataMap = BeanUtil.beanToMap(businessAssayTaskDataExtendRespVO);
			@SuppressWarnings("unchecked")
			Map<String,Object> businessAssayTaskDataAssessmentMap = BeanUtil.copyProperties(businessAssayTaskDataMap, Map.class);
			businessAssayTaskDataAssessmentMap.put("assayOperator", "判定结果");
			businessAssayTaskDataAssessmentMap.put("reportTime", null);
			businessAssayTaskDataAssessmentMap.put("assessmentStatus", QmsCommonConstant.IN_PROGRESS);

			//查询是否已添加过判定记录
			Map<String,Object> assessmentMap = dataList.stream().filter(f -> 
							    Objects.equals(businessAssayTaskDataExtendRespVO.getBusinessSubSampleId(), f.get("businessSubSampleId")) &&
							    Objects.equals(businessAssayTaskDataExtendRespVO.getConfigAssayMethodId(), f.get("configAssayMethodId")) &&
							    "判定结果".equals(f.get("assayOperator"))
							).findFirst().orElse(null);
			//为空则未添加过判定记录
			if (assessmentMap == null) {
				if (QmsCommonConstant.ASSAY_TYPE_SINGLE_PARALLEL.equals(businessAssayTaskDataExtendRespVO.getAssayType())) {//平行
					List<BusinessSubSampleAssessmentProjectExtendRespVO> businessSubSampleAssessmentList = businessSubSampleAssessmentProjectMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndRetestCount(businessAssayTaskDataExtendRespVO.getBusinessSubSampleId(), configAssayMethodId, businessAssayTaskDataExtendRespVO.getRetestCount());
					for (BusinessSubSampleAssessmentProjectExtendRespVO businessSubSampleAssessment : businessSubSampleAssessmentList) {
						businessAssayTaskDataAssessmentMap.put("id", businessSubSampleAssessment.getId());
						businessAssayTaskDataAssessmentMap.put("assessmentStatus", businessSubSampleAssessment.getAssessmentStatus());
						businessAssayTaskDataAssessmentMap.put("assessmentStatus_" + businessSubSampleAssessment.getSimpleName(), businessSubSampleAssessment.getAssessmentStatus());
						businessAssayTaskDataAssessmentMap.put(businessSubSampleAssessment.getSimpleName(), businessSubSampleAssessment.getAssessmentValue());
						businessAssayTaskDataAssessmentMap.put("assessmentValue", businessSubSampleAssessment.getAssessmentValue());
					}
				} else if (QmsCommonConstant.ASSAY_TYPE_DOUBLE_CUP.equals(businessAssayTaskDataExtendRespVO.getAssayType())) {//双杯
					//businessTeamAssessmentMapper.selectBy
				}
				dataList.add(businessAssayTaskDataAssessmentMap);
				//赋值
				assessmentMap = businessAssayTaskDataAssessmentMap;
			}
			
			
			List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataId(businessAssayTaskDataExtendRespVO.getId());
			for (BusinessAssayProjectDataExtendRespVO businessAssayProjectData : businessAssayProjectDataList) {
//				String value = businessAssayProjectData.getValueAfter();
//			    if (businessAssayProjectData.getCoefficient() != null) {
//					value = value + "(" + businessAssayProjectData.getValue() + "x" + businessAssayProjectData.getCoefficient().setScale(3, RoundingMode.HALF_EVEN).toPlainString()+ ")";
//				}
//			    businessAssayTaskDataMap.put(businessAssayProjectData.getSimpleName(), value);
				businessAssayTaskDataMap.put(businessAssayProjectData.getSimpleName(), businessAssayProjectData.getValueAfter());
//				businessAssayTaskDataMap.put(businessAssayProjectData.getSimpleName(), businessAssayProjectData.getValue());
//				businessAssayTaskDataMap.put(businessAssayProjectData.getSimpleName() + "_coefficient", businessAssayProjectData.getCoefficient());
//				businessAssayTaskDataMap.put(businessAssayProjectData.getSimpleName() + "_after", businessAssayProjectData.getValueAfter());
				businessAssayTaskDataMap.put("isNotAssessment_" + businessAssayProjectData.getSimpleName(), businessAssayProjectData.getIsNotAssessment());
				//添加判定状态
				businessAssayTaskDataMap.put("assessmentStatus", assessmentMap.get("assessmentStatus"));
				
			}
			dataList.add(businessAssayTaskDataMap);
			
		}
				
		
		JSONObject json = new JSONObject();
		json.put("columns", columnList);
		json.put("datas", dataList);
		return json;
	}

	@Override
	public JSONObject getParallelResultAssessment(Long businessSubSampleId, Long configAssayMethodId) {
		List<Map<String, Object>> columnList = new ArrayList<>();
		List<Map<String, Object>> dataList = new ArrayList<>();
		
		//查询子样平行分析结果
		BusinessAssayProjectDataReqVO search = new BusinessAssayProjectDataReqVO();
		search.setBusinessSubSampleId(businessSubSampleId);
		search.setConfigAssayMethodId(configAssayMethodId);
		List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataList = businessAssayProjectDataMapper.selectAnalysisBy(search);

		List<DictionaryBusinessExtendRespVO> assessmenTypeList = dictionaryBusinessMapper.selectItemByCategoryKeys(Arrays.asList("assessmenType"));
		for (BusinessAssayProjectDataExtendRespVO businessAssayProjectDataExtendRespVO : businessAssayProjectDataList) {
			DictionaryBusinessExtendRespVO assessmenType = assessmenTypeList.stream().filter(f -> f.getKey().equals(businessAssayProjectDataExtendRespVO.getAssessmentType())).findFirst().orElse(null);
			if (assessmenType != null) {
				businessAssayProjectDataExtendRespVO.setAssessmentTypeName(assessmenType.getName());
			}
		}
		
		
		//已检测项目分组，取第一个
		Map<Long, List<BusinessAssayProjectDataExtendRespVO>> businessAssayProjectDataMap = businessAssayProjectDataList.stream().collect(Collectors.groupingBy(BusinessAssayProjectDataExtendRespVO::getConfigAssayMethodProjectId));
		for (Map.Entry<Long, List<BusinessAssayProjectDataExtendRespVO>> businessAssayProjectDataEntry : businessAssayProjectDataMap.entrySet()) {
			//单个检测项目的分析结果
			List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataSingleList = businessAssayProjectDataEntry.getValue();
			for (BusinessAssayProjectDataExtendRespVO businessAssayProjectDataExtendRespVO : businessAssayProjectDataSingleList) {//每个检测结果作为一个动态列
				columnList.add(new HashMap<String, Object>() {
					private static final long serialVersionUID = -1844858000003248901L;

				{
					put("title", businessAssayProjectDataExtendRespVO.getSampleAssayCode() + "(" + businessAssayProjectDataExtendRespVO.getAssayOperator() + ")");
					put("field", businessAssayProjectDataExtendRespVO.getBusinessAssayTaskDataId() + ";" + businessAssayProjectDataExtendRespVO.getBusinessSubSampleId() + ";" + businessAssayProjectDataExtendRespVO.getRecheckCount());
				}});
			}
			
			//取第一个后跳出循环
			break;
		}
		
		//查询判定值
		List<BusinessSubSampleAssessmentProjectExtendRespVO> businessSubSampleAssessmentList = businessSubSampleAssessmentProjectMapper.selectByBusinessSubSampleIdAndConfigAssayMethodId(businessSubSampleId, configAssayMethodId);
		
		for (BusinessSubSampleAssessmentProjectExtendRespVO businessSubSampleAssessment : businessSubSampleAssessmentList) {
			Map<String, Object> businessSubSampleAssessmentMap = BeanUtil.beanToMap(businessSubSampleAssessment);
			List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataSingleList = businessAssayProjectDataList.stream().filter(f -> f.getDictionaryProjectId().equals(businessSubSampleAssessment.getDictionaryProjectId())).collect(Collectors.toList());
			for (BusinessAssayProjectDataExtendRespVO businessAssayProjectDataExtendRespVO : businessAssayProjectDataSingleList) {
//				String value = businessAssayProjectDataExtendRespVO.getValueAfter();
//				if (businessAssayProjectDataExtendRespVO.getCoefficient() != null) {
//					value = value + "(" + businessAssayProjectDataExtendRespVO.getValue() + "x" + businessAssayProjectDataExtendRespVO.getCoefficient().setScale(3, RoundingMode.HALF_EVEN).toPlainString()+ ")";
//				}
//				businessSubSampleAssessmentMap.put(businessAssayProjectDataExtendRespVO.getBusinessAssayTaskDataId() + ";" + businessAssayProjectDataExtendRespVO.getBusinessSubSampleId() + ";" + businessAssayProjectDataExtendRespVO.getRecheckCount(), value);
				businessSubSampleAssessmentMap.put(businessAssayProjectDataExtendRespVO.getBusinessAssayTaskDataId() + ";" + businessAssayProjectDataExtendRespVO.getBusinessSubSampleId() + ";" + businessAssayProjectDataExtendRespVO.getRecheckCount(), businessAssayProjectDataExtendRespVO.getValueAfter());
			}
			dataList.add(businessSubSampleAssessmentMap);
		}
		BusinessSubSampleDO businessSubSampleDO = businessSubSampleMapper.selectById(businessSubSampleId);
		ConfigSubSampleMethodExtendRespVO configSubSampleMethodExtendRespVO = configSubSampleMethodMapper.selectByConfigSubSampleIdAndConfigAssayMethodId(businessSubSampleDO.getConfigSubSampleId(), configAssayMethodId);
		
		
		JSONObject json = new JSONObject();
		json.put("configSubSampleMethod", configSubSampleMethodExtendRespVO);
		json.put("columns", columnList);
		json.put("datas", dataList);
		json.put("subDatas", businessAssayProjectDataList);
		return json;
	}

	@Override
	public JSONObject getDoubleCupResultAssessment(Long businessSubParentSampleId, Long configAssayMethodId) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public JSONObject getCrossAuditDataByTaskId(Long businessAssayTaskId) {
		return getCrossAuditDataByTaskId(businessAssayTaskId, null);
	}
	
	@Override
	public JSONObject getCrossAuditDataByTaskId(Long businessAssayTaskId, List<Long> businessAssayTaskDataIdList) {
		JSONWriter.Context context = JSONFactory.createWriteContext();
		context.setDateFormat("yyyy-MM-dd HH:mm:ss");
		
		JSONObject resultJsonObject = new JSONObject();
		
		BusinessAssayTaskExtendRespVO businessAssayTaskDO = businessAssayTaskMapper.selectBusinessAssayTaskById(businessAssayTaskId);
		if (businessAssayTaskDO == null) {
			throw new ServiceException(1_032_100_000, "未找到任务分配单");
		}
		//原始记录数据类型
		String reportDataType = businessAssayTaskDO.getReportDataType();
		
		JSONArray jsonArray = new JSONArray();

		String jsonString = JSON.toJSONString(businessAssayTaskDO, context);
		JSONObject businessAssayTaskJson = JSON.parseObject(jsonString);
		
		String formValue = businessAssayTaskDO.getFormValue();
		if (StringUtils.isNotBlank(formValue)) {
			JSONObject formValueJsonObject = JSON.parseObject(formValue);
			formValueJsonObject.forEach((key, value) -> {
				businessAssayTaskJson.put(key, value);
			});
		}
		jsonArray.add(businessAssayTaskJson);
		resultJsonObject.put("businessAssayTask", jsonArray);

		//处理数据
        List<Map<String, Object>> datas = new ArrayList<>();
        //横向数据
		if ("horizontal".equals(reportDataType)) {

	        List<BusinessAssayTaskDetailDO> businessAssayTaskDetailList = businessAssayTaskDetailMapper.selectByBusinessAssayTaskId(businessAssayTaskDO.getId());  
//	        List<BusinessAssayTaskDetailDO> businessAssayTaskDetailList = businessAssayTaskDetailMapper.selectList(new LambdaQueryWrapperX<BusinessAssayTaskDetailDO>().eq(BusinessAssayTaskDetailDO::getBusinessAssayTaskId, businessAssayTaskDO.getId())); 
//	        List<BusinessAssayTaskDataDO> businessAssayTaskDataList = businessAssayTaskDataMapper.selectList(new LambdaQueryWrapperX<BusinessAssayTaskDataDO>().eq(BusinessAssayTaskDataDO::getBusinessAssayTaskId, businessAssayTaskDO.getId()).eq(BusinessAssayTaskDataDO::getConfigAssayMethodId, businessAssayTaskDO.getConfigAssayMethodId()));
	        List<BusinessAssayTaskDataDO> businessAssayTaskDataList = businessAssayTaskDataMapper.selectByBusinessAssayTaskId(businessAssayTaskId);
	        if (CollUtil.isNotEmpty(businessAssayTaskDataIdList)) {//如果只显示对应的分析任务
	        	businessAssayTaskDetailList = businessAssayTaskDetailList.stream().filter(f -> businessAssayTaskDataIdList.contains(f.getBusinessAssayTaskDataId())).collect(Collectors.toList());
			}
	        
	        for (BusinessAssayTaskDetailDO businessAssayTaskDetailDO : businessAssayTaskDetailList) {
	            Map<String, Object> map = new HashedMap<>();

	            map.put("businessAssayTaskDetailId", businessAssayTaskDetailDO.getId());
	            map.put("sampleCode", businessAssayTaskDetailDO.getSampleCode());
	            map.put("sampleName", businessAssayTaskDetailDO.getSampleName());
	            map.put("analysisType", "analysis");
	            map.put("assayTime", businessAssayTaskJson.get("assayTime"));
	            map.put("taskDetailRemark", businessAssayTaskDetailDO.getRemark());
	            
	        	if (!"returned".equals(businessAssayTaskDetailDO.getRollbackStatus())) {
	        		BusinessAssayTaskDataDO businessAssayTaskDataDO = businessAssayTaskDataList.stream().filter(f -> businessAssayTaskDetailDO.getBusinessAssayTaskDataId().equals(f.getId())).findFirst().orElse(null);
		            map.put("businessAssayTaskDataId", businessAssayTaskDataDO.getId());
		            map.put("businessAssayTaskId", businessAssayTaskDataDO.getBusinessAssayTaskId());
		            map.put("businessSubSampleId", businessAssayTaskDataDO.getBusinessSubSampleId());
		            map.put("businessSubParentSampleId", businessAssayTaskDataDO.getBusinessSubParentSampleId());
		            map.put("configAssayMethodId", businessAssayTaskDataDO.getConfigAssayMethodId());
		            
		            List<BusinessAssayProjectAndParameterRespVO> businessAssayTaskParameterDataList = businessAssayTaskParameterDataMapper.selectByBusinessAssayTaskDataIds(Arrays.asList(businessAssayTaskDataDO.getId()));
		            for (BusinessAssayProjectAndParameterRespVO businessAssayTaskParameterDataDO : businessAssayTaskParameterDataList) {
						map.put(businessAssayTaskParameterDataDO.getName(), businessAssayTaskParameterDataDO.getValue());
					}

		            BusinessAssayProjectDataReqVO projectDataSearch2 = new BusinessAssayProjectDataReqVO();
		            projectDataSearch2.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
		            List<BusinessAssayProjectAndParameterRespVO> projectAndParameterList2 = businessAssayProjectDataMapper.selectProjectAndParameterBy(projectDataSearch2);
		            for (BusinessAssayProjectAndParameterRespVO ep : projectAndParameterList2) {
	                	String ev = ep.getValue();
	                	if (StringUtils.isNotBlank(ep.getSymbol()) && !"=".equals(ep.getSymbol())) {
	                		ev = ep.getSymbol() + ev;
						}
		            	map.put(ep.getName(), ev);
						if (StringUtils.isNotEmpty(ep.getFormula())) {
			        		BusinessAssayParameterDataReqVO parameterDataSearch = new BusinessAssayParameterDataReqVO();
			        		parameterDataSearch.setBusinessAssayProjectDataId(ep.getId());
			                List<BusinessAssayProjectAndParameterRespVO> plist = businessAssayParameterDataMapper.selectProjectAndParameterBy(parameterDataSearch);
			                for (BusinessAssayProjectAndParameterRespVO p : plist) {
			                	String v = p.getValue();
			                	if (StringUtils.isNotBlank(p.getSymbol()) && !"=".equals(p.getSymbol())) {
									v = p.getSymbol() + v;
								}
			                	map.put(p.getName(), v);
							}
						}
						
					}
				}
	        	
	            datas.add(map);
	        }

			List<BusinessQCManagementDataDO> businessQCManagementDataDOList = businessQCManagementDataMapper.selectByBusinessAssayTaskId(businessAssayTaskDO.getId());
			

	        for (BusinessQCManagementDataDO businessQCManagementData : businessQCManagementDataDOList) {
	            Map<String, Object> map = new HashedMap<>();
	            map.put("businessAssayTaskDataId", businessQCManagementData.getId());
	            map.put("businessAssayTaskId", businessQCManagementData.getBusinessAssayTaskId());
	            map.put("businessSubSampleId", "");
	            map.put("businessSubParentSampleId", "");
	            map.put("configAssayMethodId", businessQCManagementData.getConfigAssayMethodId());
	            map.put("businessAssayTaskDetailId", "");
	            map.put("sampleCode", businessQCManagementData.getSampleCode());
	            map.put("sampleName", businessQCManagementData.getSampleName());
	            map.put("analysisType", businessQCManagementData.getDictionaryBusinessKey());
	            map.put("assayTime", businessAssayTaskJson.get("assayTime"));
	            
	            List<BusinessAssayProjectAndParameterRespVO> businessQCManagementSampleParameterDataList = businessQCManagementSampleParameterDataMapper.selectByBusinessQCManagementDataIds(Arrays.asList(businessQCManagementData.getId()));
	            for (BusinessAssayProjectAndParameterRespVO businessQCManagementSampleParameterData : businessQCManagementSampleParameterDataList) {
					map.put(businessQCManagementSampleParameterData.getName(), businessQCManagementSampleParameterData.getValue());
				}

	            BusinessQCManagementProjectDataReqVO projectDataSearch2 = new BusinessQCManagementProjectDataReqVO();
	            projectDataSearch2.setBusinessQCManagementDataId(businessQCManagementData.getId());
	            List<BusinessAssayProjectAndParameterRespVO> projectAndParameterList2 = businessQCManagementProjectDataMapper.selectProjectAndParameterBy(projectDataSearch2);
	            for (BusinessAssayProjectAndParameterRespVO ep : projectAndParameterList2) {
                	String ev = ep.getValue();
                	if (StringUtils.isNotBlank(ep.getSymbol()) && !"=".equals(ep.getSymbol())) {
                		ev = ep.getSymbol() + ev;
					}
	            	map.put(ep.getName(), ev);
					if (StringUtils.isNotEmpty(ep.getFormula())) {
						BusinessQCManagementParameterDataReqVO parameterDataSearch = new BusinessQCManagementParameterDataReqVO();
		        		parameterDataSearch.setBusinessQCManagementProjectDataId(ep.getId());
		                List<BusinessAssayProjectAndParameterRespVO> plist = businessQCManagementParameterDataMapper.selectProjectAndParameterBy(parameterDataSearch);
		                for (BusinessAssayProjectAndParameterRespVO p : plist) {
		                	String v = p.getValue();
		                	if (StringUtils.isNotBlank(p.getSymbol()) && !"=".equals(p.getSymbol())) {
								v = p.getSymbol() + v;
							}
		                	map.put(p.getName(), v);
						}
					}
					
				}
	            datas.add(map);
			}
	        
	        List<BusinessQCCoefficientDataDO> businessQCCoefficientDataDOList = businessQCCoefficientDataMapper.selectByBusinessAssayTaskId(businessAssayTaskDO.getId());
			for (BusinessQCCoefficientDataDO businessQCCoefficientData: businessQCCoefficientDataDOList) {
	            Map<String, Object> map = new HashedMap<>();
	            map.put("businessAssayTaskDataId", businessQCCoefficientData.getId());
	            map.put("businessAssayTaskId", businessQCCoefficientData.getBusinessAssayTaskId());
	            map.put("businessSubSampleId", "");
	            map.put("businessSubParentSampleId", "");
	            map.put("configAssayMethodId", businessQCCoefficientData.getConfigAssayMethodId());
	            map.put("businessAssayTaskDetailId", "");
	            map.put("sampleCode", businessQCCoefficientData.getSampleCode());
	            map.put("sampleName", businessQCCoefficientData.getSampleName());
	            map.put("analysisType", businessQCCoefficientData.getDictionaryBusinessKey());
	            map.put("assayTime", businessAssayTaskJson.get("assayTime"));

	            BusinessQCCoefficientParameterDataReqVO parameterDataSearch2 = new BusinessQCCoefficientParameterDataReqVO();
	            parameterDataSearch2.setBusinessQCCoefficientDataId(businessQCCoefficientData.getId());
	            List<BusinessAssayProjectAndParameterRespVO> plist2 = businessQCCoefficientParameterDataMapper.selectProjectAndParameterBy(parameterDataSearch2);
	            for (BusinessAssayProjectAndParameterRespVO p : plist2) {
                	String v = p.getValue();
                	if (StringUtils.isNotBlank(p.getSymbol()) && !"=".equals(p.getSymbol())) {
						v = p.getSymbol() + v;
					}
	            	map.put(p.getName(), v);
				}
	            datas.add(map);
			}
			
		} else if ("vertical".equals(reportDataType)) {//纵向数据
			List<BusinessAssayTaskDetailDO> businessAssayTaskDetailList = businessAssayTaskDetailMapper.selectByBusinessAssayTaskId(businessAssayTaskDO.getId()); 
//			List<BusinessAssayTaskDetailDO> businessAssayTaskDetailList = businessAssayTaskDetailMapper.selectList(new LambdaQueryWrapperX<BusinessAssayTaskDetailDO>().eq(BusinessAssayTaskDetailDO::getBusinessAssayTaskId, businessAssayTaskDO.getId()));
//	        List<BusinessAssayTaskDataDO> businessAssayTaskDataList = businessAssayTaskDataMapper.selectList(new LambdaQueryWrapperX<BusinessAssayTaskDataDO>().eq(BusinessAssayTaskDataDO::getBusinessAssayTaskId, businessAssayTaskDO.getId()).eq(BusinessAssayTaskDataDO::getConfigAssayMethodId, businessAssayTaskDO.getConfigAssayMethodId()));
			List<BusinessAssayTaskDataDO> businessAssayTaskDataList = businessAssayTaskDataMapper.selectByBusinessAssayTaskId(businessAssayTaskId);
			if (CollUtil.isNotEmpty(businessAssayTaskDataIdList)) {//如果只显示对应的分析任务
	        	businessAssayTaskDetailList = businessAssayTaskDetailList.stream().filter(f -> businessAssayTaskDataIdList.contains(f.getBusinessAssayTaskDataId())).collect(Collectors.toList());
			}
	        for (BusinessAssayTaskDetailDO businessAssayTaskDetailDO : businessAssayTaskDetailList) {
	        	//BusinessAssayTaskDetailDO businessAssayTaskDetailDO = businessAssayTaskDetailList.stream().filter(f -> f.getSampleId().equals(businessAssayTaskDataDO.getBusinessSubSampleId())).findFirst().orElse(null);
	        	
	        	HashedMap<String, Object> map = new HashedMap<>();
	            map.put("businessAssayTaskDetailId", businessAssayTaskDetailDO.getId());
	            map.put("sampleCode", businessAssayTaskDetailDO.getSampleCode());
	            map.put("sampleName", businessAssayTaskDetailDO.getSampleName());
	            map.put("analysisType", "analysis");
	            map.put("assayTime", businessAssayTaskJson.get("assayTime"));
	            map.put("taskDetailRemark", businessAssayTaskDetailDO.getRemark());
	            

	        	if (!"returned".equals(businessAssayTaskDetailDO.getRollbackStatus())) {
	        		BusinessAssayTaskDataDO businessAssayTaskDataDO = businessAssayTaskDataList.stream().filter(f -> businessAssayTaskDetailDO.getBusinessAssayTaskDataId().equals(f.getId())).findFirst().orElse(null);

		            map.put("businessAssayTaskDataId", businessAssayTaskDataDO.getId());
		            map.put("businessAssayTaskId", businessAssayTaskDataDO.getBusinessAssayTaskId());
		            map.put("businessSubSampleId", businessAssayTaskDataDO.getBusinessSubSampleId());
		            map.put("businessSubParentSampleId", businessAssayTaskDataDO.getBusinessSubParentSampleId());
		            map.put("configAssayMethodId", businessAssayTaskDataDO.getConfigAssayMethodId());
		            
		            List<BusinessAssayProjectAndParameterRespVO> businessAssayTaskParameterDataList = businessAssayTaskParameterDataMapper.selectByBusinessAssayTaskDataIds(Arrays.asList(businessAssayTaskDataDO.getId()));
		            for (BusinessAssayProjectAndParameterRespVO businessAssayTaskParameterDataDO : businessAssayTaskParameterDataList) {
						map.put(businessAssayTaskParameterDataDO.getName(), businessAssayTaskParameterDataDO.getValue());
					}

		            BusinessAssayProjectDataReqVO projectDataSearch2 = new BusinessAssayProjectDataReqVO();
		            projectDataSearch2.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
		            List<BusinessAssayProjectAndParameterRespVO> projectAndParameterList2 = businessAssayProjectDataMapper.selectProjectAndParameterBy(projectDataSearch2);
		            for (BusinessAssayProjectAndParameterRespVO ep : projectAndParameterList2) {
		            	HashedMap<String, Object> newMap = SerializationUtils.clone(map);
		            	String projectSymbol = "";
		            	if (StringUtils.isNotBlank(ep.getSymbol()) && !"=".equals(ep.getSymbol())) {
		            		projectSymbol = ep.getSymbol();
						}
//		            	newMap.put(ep.getName(), ep.getValue());
		            	newMap.put("projectName", ep.getShowName());
		            	newMap.put("projectValue", ep.getValue());
		            	newMap.put("projectSymbol", projectSymbol);
		            	newMap.put("projectUnit", ep.getUnit());
						if (StringUtils.isNotEmpty(ep.getFormula())) {
			        		BusinessAssayParameterDataReqVO parameterDataSearch = new BusinessAssayParameterDataReqVO();
			        		parameterDataSearch.setBusinessAssayProjectDataId(ep.getId());
			                List<BusinessAssayProjectAndParameterRespVO> plist = businessAssayParameterDataMapper.selectProjectAndParameterBy(parameterDataSearch);
			                for (BusinessAssayProjectAndParameterRespVO p : plist) {
			                	String v = p.getValue();
			                	if (StringUtils.isNotBlank(p.getSymbol()) && !"=".equals(p.getSymbol())) {
									v = p.getSymbol() + v;
								}
			                	newMap.put(p.getName(), v);
							}
						}
			            datas.add(newMap);
					}
	        		
	        	} else {
	        		datas.add(map);
				}

	        }

			List<BusinessQCManagementDataDO> businessQCManagementDataDOList = businessQCManagementDataMapper.selectByBusinessAssayTaskId(businessAssayTaskDO.getId());
			

	        for (BusinessQCManagementDataDO businessQCManagementData : businessQCManagementDataDOList) {
	        	HashedMap<String, Object> map = new HashedMap<>();
	            map.put("businessAssayTaskDataId", businessQCManagementData.getId());
	            map.put("businessAssayTaskId", businessQCManagementData.getBusinessAssayTaskId());
	            map.put("businessSubSampleId", "");
	            map.put("businessSubParentSampleId", "");
	            map.put("configAssayMethodId", businessQCManagementData.getConfigAssayMethodId());
	            map.put("businessAssayTaskDetailId", "");
	            map.put("sampleCode", businessQCManagementData.getSampleCode());
	            map.put("sampleName", businessQCManagementData.getSampleName());
	            map.put("analysisType", businessQCManagementData.getDictionaryBusinessKey());
	            map.put("assayTime", businessAssayTaskJson.get("assayTime"));
	            
	            List<BusinessAssayProjectAndParameterRespVO> businessQCManagementSampleParameterDataList = businessQCManagementSampleParameterDataMapper.selectByBusinessQCManagementDataIds(Arrays.asList(businessQCManagementData.getId()));
	            for (BusinessAssayProjectAndParameterRespVO businessQCManagementSampleParameterData : businessQCManagementSampleParameterDataList) {
                	String v = businessQCManagementSampleParameterData.getValue();
                	if (StringUtils.isNotBlank(businessQCManagementSampleParameterData.getSymbol()) && !"=".equals(businessQCManagementSampleParameterData.getSymbol())) {
						v = businessQCManagementSampleParameterData.getSymbol() + v;
					}
					map.put(businessQCManagementSampleParameterData.getName(), v);
				}

	            BusinessQCManagementProjectDataReqVO projectDataSearch2 = new BusinessQCManagementProjectDataReqVO();
	            projectDataSearch2.setBusinessQCManagementDataId(businessQCManagementData.getId());
	            List<BusinessAssayProjectAndParameterRespVO> projectAndParameterList2 = businessQCManagementProjectDataMapper.selectProjectAndParameterBy(projectDataSearch2);
	            for (BusinessAssayProjectAndParameterRespVO ep : projectAndParameterList2) {
	            	HashedMap<String, Object> newMap = SerializationUtils.clone(map);
	            	String projectSymbol = "";
	            	if (StringUtils.isNotBlank(ep.getSymbol()) && !"=".equals(ep.getSymbol())) {
	            		projectSymbol = ep.getSymbol();
					}
//	            	newMap.put(ep.getName(), ep.getValue());
	            	newMap.put("projectName", ep.getShowName());
	            	newMap.put("projectValue", ep.getValue());
	            	newMap.put("projectSymbol", projectSymbol);
	            	newMap.put("projectUnit", ep.getUnit());
					if (StringUtils.isNotEmpty(ep.getFormula())) {
						BusinessQCManagementParameterDataReqVO parameterDataSearch = new BusinessQCManagementParameterDataReqVO();
		        		parameterDataSearch.setBusinessQCManagementProjectDataId(ep.getId());
		                List<BusinessAssayProjectAndParameterRespVO> plist = businessQCManagementParameterDataMapper.selectProjectAndParameterBy(parameterDataSearch);
		                for (BusinessAssayProjectAndParameterRespVO p : plist) {
		                	String v = p.getValue();
		                	if (StringUtils.isNotBlank(p.getSymbol()) && !"=".equals(p.getSymbol())) {
								v = p.getSymbol() + v;
							}
		                	newMap.put(p.getName(), v);
						}
					}
		            datas.add(newMap);
				}
			}
	        
	        List<BusinessQCCoefficientDataDO> businessQCCoefficientDataDOList = businessQCCoefficientDataMapper.selectByBusinessAssayTaskId(businessAssayTaskDO.getId());
			for (BusinessQCCoefficientDataDO businessQCCoefficientData: businessQCCoefficientDataDOList) {
				HashedMap<String, Object> map = new HashedMap<>();
	            map.put("businessAssayTaskDataId", businessQCCoefficientData.getId());
	            map.put("businessAssayTaskId", businessQCCoefficientData.getBusinessAssayTaskId());
	            map.put("businessSubSampleId", "");
	            map.put("businessSubParentSampleId", "");
	            map.put("configAssayMethodId", businessQCCoefficientData.getConfigAssayMethodId());
	            map.put("businessAssayTaskDetailId", "");
	            map.put("sampleCode", businessQCCoefficientData.getSampleCode());
	            map.put("sampleName", businessQCCoefficientData.getSampleName());
	            map.put("analysisType", businessQCCoefficientData.getDictionaryBusinessKey());
	            map.put("assayTime", businessAssayTaskJson.get("assayTime"));

	            BusinessQCCoefficientParameterDataReqVO parameterDataSearch2 = new BusinessQCCoefficientParameterDataReqVO();
	            parameterDataSearch2.setBusinessQCCoefficientDataId(businessQCCoefficientData.getId());
	            List<BusinessAssayProjectAndParameterRespVO> plist2 = businessQCCoefficientParameterDataMapper.selectProjectAndParameterBy(parameterDataSearch2);
	            for (BusinessAssayProjectAndParameterRespVO p : plist2) {
	            	String projectSymbol = "";
	            	if (StringUtils.isNotBlank(p.getSymbol()) && !"=".equals(p.getSymbol())) {
	            		projectSymbol = p.getSymbol();
					}
	            	//map.put(p.getName(), p.getValue());
	            	HashedMap<String, Object> newMap = SerializationUtils.clone(map);
	            	newMap.put("projectName", p.getShowName());
	            	newMap.put("projectValue", p.getValue());
	            	newMap.put("projectSymbol", projectSymbol);
	            	newMap.put("projectUnit", p.getUnit());
		            datas.add(map);
				}
			}
			
		}
		

//		resultJsonObject.put("all", datas);
//		Map<String, List<Map<String, Object>>> map = datas.stream().collect(Collectors.groupingBy(g -> (String) g.get("analysisType")));
//		for (Map.Entry<String, List<Map<String, Object>>> entry : map.entrySet()) {
//			resultJsonObject.put(entry.getKey(), entry.getValue());
//		}

		List<Map<String, Object>> fxList = datas.stream().filter(f -> "analysis".equals(f.get("analysisType")) || "zky".equals(f.get("analysisType")) || "kby".equals(f.get("analysisType")) || "zkkby".equals(f.get("analysisType")) || "jky".equals(f.get("analysisType")) ).collect(Collectors.toList());
		resultJsonObject.put("fx", fxList);
		List<Map<String, Object>> byList = datas.stream().filter(f -> "by".equals(f.get("analysisType"))).collect(Collectors.toList());
		resultJsonObject.put("by", byList);		
		return resultJsonObject;
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void crossAuditByTaskId(Long businessAssayTaskId, String auditStatus) {

		//当前登录用户昵称
		String nickName = SecurityFrameworkUtils.getLoginUserNickname();
		
		//自动上报的子样判定数据
		List<BusinessSubSampleAssessmentDO> automaticBusinessSubSampleAssessmentList = new ArrayList<>();
		
		//分析检测项目记录
		List<BusinessAssayProjectDataDO> updateBusinessAssayProjectDataDOList = new ArrayList<>();
		//判定记录
		List<BusinessSubSampleAssessmentDO> updateBusinessSubSampleAssessmentDOList = new ArrayList<>();
		List<BusinessSubSampleAssessmentProjectDO> saveBusinessSubSampleAssessmentProjectDOList = new ArrayList<>();
		List<BusinessSubSampleAssessmentProjectDO> updateBusinessSubSampleAssessmentProjectDOList = new ArrayList<>();
		
		BusinessAssayTaskDO businessAssayTaskDO = businessAssayTaskMapper.selectById(businessAssayTaskId);
		if (QmsCommonConstant.APPROVE.equals(auditStatus)) {
			businessAssayTaskDO.setFinishStatus(QmsCommonConstant.COMPLETED);
			businessAssayTaskDO.setFlowStatus(QmsCommonConstant.COMPLETED);
			businessAssayTaskDO.setReportTime(LocalDateTime.now());
			businessAssayTaskDO.setReportOperator(SecurityFrameworkUtils.getLoginUserNickname());
			businessAssayTaskDO.setReportOperatorId(SecurityFrameworkUtils.getLoginUserId());
			
			//查询分析任务明细
			List<BusinessAssayTaskDataDO> businessAssayTaskDataDOList = businessAssayTaskDataMapper.selectByBusinessAssayTaskId(businessAssayTaskId);
			
			//获取任务明细对应的判定id
			List<Long> businessSubSampleAssessmentIdList = businessAssayTaskDataDOList.stream().map(m -> m.getBusinessSubSampleAssessmentId()).distinct().collect(Collectors.toList());
			//获取子样判定数据
			List<BusinessSubSampleAssessmentDO> businessSubSampleAssessmentDOList = businessSubSampleAssessmentMapper.selectByIds(businessSubSampleAssessmentIdList);
			
			//根据子样分组
			Map<Long, List<BusinessAssayTaskDataDO>> businessAssayTaskDataDOMap = businessAssayTaskDataDOList.stream().collect(Collectors.groupingBy(BusinessAssayTaskDataDO::getBusinessSubSampleId));
			//循环分组
			for (Map.Entry<Long, List<BusinessAssayTaskDataDO>> businessAssayTaskDataDOMapEntry : businessAssayTaskDataDOMap.entrySet()) {
				
				Long businessSubSampleId = businessAssayTaskDataDOMapEntry.getKey();
				List<BusinessAssayTaskDataDO> businessAssayTaskDataList = businessAssayTaskDataDOMapEntry.getValue();
				
				Map<Integer, List<BusinessAssayTaskDataDO>> businessAssayTaskDataDORetestMap = businessAssayTaskDataList.stream().collect(Collectors.groupingBy(BusinessAssayTaskDataDO::getRetestCount));
				
				for (Map.Entry<Integer, List<BusinessAssayTaskDataDO>> businessAssayTaskDataDORetestMapEntry : businessAssayTaskDataDORetestMap.entrySet()) {
					Integer retestCount = businessAssayTaskDataDORetestMapEntry.getKey();
					List<BusinessAssayTaskDataDO> businessAssayTaskDataRetestList = businessAssayTaskDataDORetestMapEntry.getValue();
					
					List<Long> businessAssayTaskDataIdList = businessAssayTaskDataRetestList.stream().map(m -> m.getId()).collect(Collectors.toList());
					BusinessAssayTaskDataDO businessAssayTaskDataDO = businessAssayTaskDataRetestList.get(0);
					
					BusinessSubSampleDO businessSubSampleDO = businessSubSampleMapper.selectById(businessSubSampleId);
					//获取子样分析方法配置
					ConfigSubSampleMethodExtendRespVO configSubSampleMethodDO = configSubSampleMethodMapper.selectByConfigSubSampleIdAndConfigAssayMethodId(businessSubSampleDO.getConfigSubSampleId(), businessAssayTaskDataDO.getConfigAssayMethodId());
									
					if (QmsCommonConstant.ASSAY_TYPE_SINGLE_PARALLEL.equals(businessAssayTaskDataDO.getAssayType())) {
						//根据子样id及分析方法id，查询未上报的分析任务
						List<BusinessAssayTaskDataDO> unReportedList = businessAssayTaskDataMapper.selectIsReportedList(businessAssayTaskDataIdList, businessAssayTaskDataDO.getBusinessSubSampleId(), businessAssayTaskDataDO.getConfigAssayMethodId(), retestCount, QmsCommonConstant.NO);
						if (unReportedList.size() > 0) {//还有未上报数据，直接处理，无需判定
							continue;
						} else {//做超差判定
							//根据子样id及分析方法id，查询已上报的分析任务
							List<BusinessAssayTaskDataDO> reportedList = businessAssayTaskDataMapper.selectIsReportedList(businessAssayTaskDataIdList, businessAssayTaskDataDO.getBusinessSubSampleId(), businessAssayTaskDataDO.getConfigAssayMethodId(), retestCount, QmsCommonConstant.YES);
							if (reportedList.size() > 0) {
								List<Long> reportedBusinessAssayTaskDataIdList = reportedList.stream().map(m -> m.getId()).collect(Collectors.toList());
								businessAssayTaskDataIdList.addAll(reportedBusinessAssayTaskDataIdList);
							}
							
							//查询判定业务
							BusinessSubSampleAssessmentDO businessSubSampleAssessmentDO = updateBusinessSubSampleAssessmentDOList.stream().filter(f -> f.getId().equals(businessAssayTaskDataDO.getBusinessSubSampleAssessmentId())).findFirst().orElse(null);
							if (businessSubSampleAssessmentDO == null) {
								businessSubSampleAssessmentDO = businessSubSampleAssessmentDOList.stream().filter(f -> f.getId().equals(businessAssayTaskDataDO.getBusinessSubSampleAssessmentId())).findFirst().orElse(null);
								updateBusinessSubSampleAssessmentDOList.add(businessSubSampleAssessmentDO);
							}
							//状态设置为待上报
			            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_REPORT);
							//查询分析项目
			            	List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataExtendList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
							Map<Long, List<BusinessAssayProjectDataExtendRespVO>> businessAssayProjectDataDOMap = businessAssayProjectDataExtendList.stream().collect(Collectors.groupingBy(BusinessAssayProjectDataExtendRespVO::getDictionaryProjectId));
							
							for (Map.Entry<Long, List<BusinessAssayProjectDataExtendRespVO>> businessAssayProjectDataDOEntry : businessAssayProjectDataDOMap.entrySet()) {
								Long dictionaryProjectId = businessAssayProjectDataDOEntry.getKey();
								List<BusinessAssayProjectDataExtendRespVO> val1 = businessAssayProjectDataDOEntry.getValue();
								BusinessAssayProjectDataExtendRespVO businessAssayProjectDataDO = val1.get(0);
								
								//查询判定结果数据
								BusinessSubSampleAssessmentProjectDO businessSubSampleAssessmentProjectDO = businessSubSampleAssessmentProjectMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndConfigAssayMethodProjectId(businessSubSampleId, businessAssayTaskDataDO.getConfigAssayMethodId(), businessAssayProjectDataDO.getConfigAssayMethodProjectId());
								if (businessSubSampleAssessmentProjectDO == null) {
									businessSubSampleAssessmentProjectDO = new BusinessSubSampleAssessmentProjectDO();

							        saveBusinessSubSampleAssessmentProjectDOList.add(businessSubSampleAssessmentProjectDO);
								} else {
									updateBusinessSubSampleAssessmentProjectDOList.add(businessSubSampleAssessmentProjectDO);
								}
								businessSubSampleAssessmentProjectDO.setBusinessSubParentSampleId(businessAssayTaskDataDO.getBusinessSubParentSampleId());
								businessSubSampleAssessmentProjectDO.setBusinessSubSampleId(businessAssayTaskDataDO.getBusinessSubSampleId());
								businessSubSampleAssessmentProjectDO.setBusinessSubSampleAssessmentId(businessSubSampleAssessmentDO.getId());
								businessSubSampleAssessmentProjectDO.setConfigAssayMethodId(businessAssayTaskDataDO.getConfigAssayMethodId());
								businessSubSampleAssessmentProjectDO.setConfigAssayMethodProjectId(businessAssayProjectDataDO.getConfigAssayMethodProjectId());
								businessSubSampleAssessmentProjectDO.setDictionaryProjectId(dictionaryProjectId);
								businessSubSampleAssessmentProjectDO.setDataType(businessAssayProjectDataDO.getDataType());
								businessSubSampleAssessmentProjectDO.setDecimalPosition(businessAssayProjectDataDO.getDecimalPosition());
								businessSubSampleAssessmentProjectDO.setEffectiveDigit(businessAssayProjectDataDO.getEffectiveDigit());
								businessSubSampleAssessmentProjectDO.setAssayType(businessAssayTaskDataDO.getAssayType());
								businessSubSampleAssessmentProjectDO.setTaskType(businessAssayTaskDataDO.getTaskType());
								businessSubSampleAssessmentProjectDO.setUsage(businessAssayProjectDataDO.getUsage());
								businessSubSampleAssessmentProjectDO.setSymbol(businessAssayProjectDataDO.getSymbol());
								businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.NORMAL);
								
								//查查超差判定配置
								List<ConfigAssayMethodProjectAssessmentDO> configAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentMapper.selectByConfigBaseSampleIdAndConfigAssayMethodIdAndConfigAssayMethodProjectId(configSubSampleMethodDO.getConfigBaseSampleId(), businessAssayTaskDataDO.getConfigAssayMethodId(), businessAssayProjectDataDO.getConfigAssayMethodProjectId());
								
								//是否复检
								boolean isRecheck = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO)).anyMatch(a -> a.getRecheckCount() > 0);
								
								//分析人员任务数map
								Map<String, Long> assayOperatorCountMap = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO)).collect(Collectors.groupingBy(BusinessAssayProjectDataExtendRespVO::getAssayOperator, Collectors.counting()));
								//分析人员数
								int assayOperatorSize = assayOperatorCountMap.size();
								
								//是否多任务
//								boolean isMultitask = assayOperatorCountMap.values().stream().allMatch(c -> c >= 2);
								
								//不是复检
								if (!isRecheck) {
									//优先查询内控，如果存在内控，则使用内控超差判定，否则根据人数确定
									//查询内控超差配置
									List<ConfigAssayMethodProjectAssessmentDO> internalControlConfigAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentDOList.stream().filter(f -> QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL.equals(f.getAssessmentType())).collect(Collectors.toList());
									if (internalControlConfigAssayMethodProjectAssessmentDOList.size() > 0) {
										 // 排序并处理 null
								        List<BigDecimal> sortedValues = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
								                .map(v -> {
								                    String val = v.getValueAfter();//补正后的值
								                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
								                })
								                .sorted()
								                .collect(Collectors.toList());
								        List<BusinessAssayProjectDataExtendRespVO> vBySortedValues = val1.stream()
								        	    .filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
								        	    // 构建 Entry: Key是原对象，Value是排序用的数字
								        	    .map(v -> {
								        	        String valStr = v.getValueAfter();
								        	        BigDecimal sortVal = (valStr == null || valStr.trim().isEmpty()) 
								        	                             ? BigDecimal.ZERO 
								        	                             : new BigDecimal(valStr.trim());
								        	        return new SimpleEntry<>(v, sortVal);
								        	    })
								        	    // 比较 Entry 的 Value 部分
								        	    .sorted(Map.Entry.comparingByValue())
								        	    // 提取 Key (原对象)
								        	    .map(Map.Entry::getKey)
								        	    .collect(Collectors.toList());
										
								        // 获取小数精度
								        int elementScale = businessAssayProjectDataDO.getDecimalPosition();
								        //获取有效位数
								        int effectiveDigit = businessAssayProjectDataDO.getEffectiveDigit();
								        // 计算代表值（均值或差值）
								        BigDecimal representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

										//计算后保留有效位数
										representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
								        //设置判定值
								        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
								        
								        // 查找匹配的允差规则
								        ConfigAssayMethodProjectAssessmentDO matchedRule = findMatchingRule(internalControlConfigAssayMethodProjectAssessmentDOList, representativeValue);
								        if (matchedRule == null) {
								            throw new ServiceException(1_032_100_000, "未找到内控超差判定区间范围，检测项目ID: " + dictionaryProjectId + ", 值: " + representativeValue);
								        }

								        // 计算允差值
								        BigDecimal allowValue;
								        try {
								            allowValue = allowanceCalculatorComponent.calculateAllowableValue(new BigDecimal(matchedRule.getMinimumValue()), new BigDecimal(matchedRule.getMaximumValue()), new BigDecimal(matchedRule.getMinimumToleraanceValue()), new BigDecimal(matchedRule.getMaximumToleraanceValue()), new BigDecimal(matchedRule.getToleraanceAdjustmentValue()), representativeValue, matchedRule.getIsUseFormula(), matchedRule.getFormula(), elementScale);
								        } catch (Exception e) {
								            throw new ServiceException(1_032_100_000, "超差判定计算出错，检测项目ID: " + dictionaryProjectId);
								        }

								        // 判断相邻差值是否超差
								        for (int i = 0; i < sortedValues.size() - 1; i++) {
								            BigDecimal diff = sortedValues.get(i + 1).subtract(sortedValues.get(i)).abs();
							            	BusinessAssayProjectDataExtendRespVO preBusinessAssayProjectDataDO = vBySortedValues.get(i);
							            	BusinessAssayProjectDataExtendRespVO curBusinessAssayProjectDataDO = vBySortedValues.get(i + 1);
								            if (diff.compareTo(allowValue) > 0) {
								            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.EXCEEDS_TOLERANCE);
								            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
								            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
												preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
												curBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
								            	
								            	//存在超差，设置为待判定
								            	if (!QmsCommonConstant.ASMT_PENDING_ASSESSMENT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
									            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_ASSESSMENT);
												}
								            } else {
								            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
								            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
											}
								        }
									} else {
										if (assayOperatorSize == 1) {//如果是单人，使用重复性。
											//过滤配置为 重复性超差
											List<ConfigAssayMethodProjectAssessmentDO> repetitivenessConfigAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentDOList.stream().filter(f -> QmsCommonConstant.ASMT_TYPE_REPETITIVENESS.equals(f.getAssessmentType())).collect(Collectors.toList());
											if (repetitivenessConfigAssayMethodProjectAssessmentDOList.size() > 0) {
												// 排序并处理 null
										        List<BigDecimal> sortedValues = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										                .map(v -> {
										                    String val = v.getValueAfter();//补正后的值
										                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
										                })
										                .sorted()
										                .collect(Collectors.toList());
										        List<BusinessAssayProjectDataExtendRespVO> vBySortedValues = val1.stream()
										        	    .filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										        	    // 构建 Entry: Key是原对象，Value是排序用的数字
										        	    .map(v -> {
										        	        String valStr = v.getValueAfter();
										        	        BigDecimal sortVal = (valStr == null || valStr.trim().isEmpty()) 
										        	                             ? BigDecimal.ZERO 
										        	                             : new BigDecimal(valStr.trim());
										        	        return new SimpleEntry<>(v, sortVal);
										        	    })
										        	    // 比较 Entry 的 Value 部分
										        	    .sorted(Map.Entry.comparingByValue())
										        	    // 提取 Key (原对象)
										        	    .map(Map.Entry::getKey)
										        	    .collect(Collectors.toList());
												
										        // 获取小数精度
										        int elementScale = businessAssayProjectDataDO.getDecimalPosition();
										        //获取有效位数
										        int effectiveDigit = businessAssayProjectDataDO.getEffectiveDigit();
										        // 计算代表值（均值或差值）
										        BigDecimal representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

												//计算后保留有效位数
												representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
										        //设置判定值
										        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
										        
										        // 查找匹配的允差规则
										        ConfigAssayMethodProjectAssessmentDO matchedRule = findMatchingRule(repetitivenessConfigAssayMethodProjectAssessmentDOList, representativeValue);
										        if (matchedRule == null) {
										            throw new ServiceException(1_032_100_000, "未找到重复性超差判定区间范围，检测项目ID: " + dictionaryProjectId + ", 值: " + representativeValue);
										        }

										        // 计算允差值
										        BigDecimal allowValue;
										        try {
										            allowValue = allowanceCalculatorComponent.calculateAllowableValue(new BigDecimal(matchedRule.getMinimumValue()), new BigDecimal(matchedRule.getMaximumValue()), new BigDecimal(matchedRule.getMinimumToleraanceValue()), new BigDecimal(matchedRule.getMaximumToleraanceValue()), new BigDecimal(matchedRule.getToleraanceAdjustmentValue()), representativeValue, matchedRule.getIsUseFormula(), matchedRule.getFormula(), elementScale);
										        } catch (Exception e) {
										            throw new ServiceException(1_032_100_000, "超差判定计算出错，检测项目ID: " + dictionaryProjectId);
										        }

										        // 判断相邻差值是否超差
										        for (int i = 0; i < sortedValues.size() - 1; i++) {
										            BigDecimal diff = sortedValues.get(i + 1).subtract(sortedValues.get(i)).abs();
									            	BusinessAssayProjectDataExtendRespVO preBusinessAssayProjectDataDO = vBySortedValues.get(i);
									            	BusinessAssayProjectDataExtendRespVO curBusinessAssayProjectDataDO = vBySortedValues.get(i + 1);
										            if (diff.compareTo(allowValue) > 0) {
										            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.EXCEEDS_TOLERANCE);
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
										            	int isCancelAssessment = matchedRule.getIsCancelAssessment();//查询配置，是否超差
										            	if (isCancelAssessment == 1) {
															preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.YES);
															preBusinessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.YES);
														} else {
															preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
															preBusinessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.NO);
														}
										            	
										            	//存在超差，设置为待判定
										            	if (!QmsCommonConstant.ASMT_PENDING_ASSESSMENT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
											            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_ASSESSMENT);
														}
										            } else {
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
													}
										        }
											} else {
												throw new ServiceException(1_032_100_000, "单人,未找到重复性超差判定配置！ ");
											}
										} else {//多人使用再现性
											//再现性超差配置
											List<ConfigAssayMethodProjectAssessmentDO> reproducibilityConfigAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentDOList.stream().filter(f -> QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY.equals(f.getAssessmentType())).collect(Collectors.toList());
											if (reproducibilityConfigAssayMethodProjectAssessmentDOList.size() > 0) {
												 // 排序并处理 null
										        List<BigDecimal> sortedValues = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										                .map(v -> {
										                    String val = v.getValueAfter();//补正后的值
										                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
										                })
										                .sorted()
										                .collect(Collectors.toList());
										        List<BusinessAssayProjectDataExtendRespVO> vBySortedValues = val1.stream()
										        	    .filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										        	    // 构建 Entry: Key是原对象，Value是排序用的数字
										        	    .map(v -> {
										        	        String valStr = v.getValueAfter();
										        	        BigDecimal sortVal = (valStr == null || valStr.trim().isEmpty()) 
										        	                             ? BigDecimal.ZERO 
										        	                             : new BigDecimal(valStr.trim());
										        	        return new SimpleEntry<>(v, sortVal);
										        	    })
										        	    // 比较 Entry 的 Value 部分
										        	    .sorted(Map.Entry.comparingByValue())
										        	    // 提取 Key (原对象)
										        	    .map(Map.Entry::getKey)
										        	    .collect(Collectors.toList());
												
										        // 获取小数精度
										        int elementScale = businessAssayProjectDataDO.getDecimalPosition();
										        //获取有效位数
										        int effectiveDigit = businessAssayProjectDataDO.getEffectiveDigit();
										        // 计算代表值（均值或差值）
										        BigDecimal representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

												//计算后保留有效位数
												representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
										        //设置判定值
										        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
										        
										        // 查找匹配的允差规则
										        ConfigAssayMethodProjectAssessmentDO matchedRule = findMatchingRule(reproducibilityConfigAssayMethodProjectAssessmentDOList, representativeValue);
										        if (matchedRule == null) {
										            throw new ServiceException(1_032_100_000, "未找到再现性超差判定区间范围，检测项目ID: " + dictionaryProjectId + ", 值: " + representativeValue);
										        }

										        // 计算允差值
										        BigDecimal allowValue;
										        try {
										            allowValue = allowanceCalculatorComponent.calculateAllowableValue(new BigDecimal(matchedRule.getMinimumValue()), new BigDecimal(matchedRule.getMaximumValue()), new BigDecimal(matchedRule.getMinimumToleraanceValue()), new BigDecimal(matchedRule.getMaximumToleraanceValue()), new BigDecimal(matchedRule.getToleraanceAdjustmentValue()), representativeValue, matchedRule.getIsUseFormula(), matchedRule.getFormula(), elementScale);
										        } catch (Exception e) {
										            throw new ServiceException(1_032_100_000, "超差判定计算出错，检测项目ID: " + dictionaryProjectId);
										        }

										        // 判断相邻差值是否超差
										        for (int i = 0; i < sortedValues.size() - 1; i++) {
										            BigDecimal diff = sortedValues.get(i + 1).subtract(sortedValues.get(i)).abs();
									            	BusinessAssayProjectDataExtendRespVO preBusinessAssayProjectDataDO = vBySortedValues.get(i);
									            	BusinessAssayProjectDataExtendRespVO curBusinessAssayProjectDataDO = vBySortedValues.get(i + 1);
										            if (diff.compareTo(allowValue) > 0) {
										            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.EXCEEDS_TOLERANCE);
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
														preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
														curBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
										            	
										            	//存在超差，设置为待判定
										            	if (!QmsCommonConstant.ASMT_PENDING_ASSESSMENT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
											            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_ASSESSMENT);
														}
										            } else {
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
													}
										        }
											} else {
												throw new ServiceException(1_032_100_000, "多人,未找到再现性超差判定配置！ ");
											}
										}
									}
								} else {//发起过复检的
									//优先查询内控，如果存在内控，则使用内控超差判定，否则根据人数确定
									//查询内控超差配置
									List<ConfigAssayMethodProjectAssessmentDO> internalControlConfigAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentDOList.stream().filter(f -> QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL.equals(f.getAssessmentType())).collect(Collectors.toList());
									if (internalControlConfigAssayMethodProjectAssessmentDOList.size() > 0) {
										 // 排序并处理 null
								        List<BigDecimal> sortedValues = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
								                .map(v -> {
								                    String val = v.getValueAfter();//补正后的值
								                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
								                })
								                .sorted()
								                .collect(Collectors.toList());
								        List<BusinessAssayProjectDataExtendRespVO> vBySortedValues = val1.stream()
								        	    .filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
								        	    // 构建 Entry: Key是原对象，Value是排序用的数字
								        	    .map(v -> {
								        	        String valStr = v.getValueAfter();
								        	        BigDecimal sortVal = (valStr == null || valStr.trim().isEmpty()) 
								        	                             ? BigDecimal.ZERO 
								        	                             : new BigDecimal(valStr.trim());
								        	        return new SimpleEntry<>(v, sortVal);
								        	    })
								        	    // 比较 Entry 的 Value 部分
								        	    .sorted(Map.Entry.comparingByValue())
								        	    // 提取 Key (原对象)
								        	    .map(Map.Entry::getKey)
								        	    .collect(Collectors.toList());
										
								        // 获取小数精度
								        int elementScale = businessAssayProjectDataDO.getDecimalPosition();
								        //获取有效位数
								        int effectiveDigit = businessAssayProjectDataDO.getEffectiveDigit();
								        // 计算代表值（均值或差值）
								        BigDecimal representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

										//计算后保留有效位数
										representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
								        //设置判定值
								        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
								        
								        // 查找匹配的允差规则
								        ConfigAssayMethodProjectAssessmentDO matchedRule = findMatchingRule(internalControlConfigAssayMethodProjectAssessmentDOList, representativeValue);
								        if (matchedRule == null) {
								            throw new ServiceException(1_032_100_000, "未找到内控超差判定区间范围，检测项目ID: " + dictionaryProjectId + ", 值: " + representativeValue);
								        }

								        // 计算允差值
								        BigDecimal allowValue;
								        try {
								            allowValue = allowanceCalculatorComponent.calculateAllowableValue(new BigDecimal(matchedRule.getMinimumValue()), new BigDecimal(matchedRule.getMaximumValue()), new BigDecimal(matchedRule.getMinimumToleraanceValue()), new BigDecimal(matchedRule.getMaximumToleraanceValue()), new BigDecimal(matchedRule.getToleraanceAdjustmentValue()), representativeValue, matchedRule.getIsUseFormula(), matchedRule.getFormula(), elementScale);
								        } catch (Exception e) {
								            throw new ServiceException(1_032_100_000, "超差判定计算出错，检测项目ID: " + dictionaryProjectId);
								        }
								        
								        List<List<BusinessAssayProjectDataExtendRespVO>> validGroups = new ArrayList<>();
								        List<BusinessAssayProjectDataExtendRespVO> currentGroup = new ArrayList<>();

								        // 判断相邻差值是否超差
								        for (int i = 0; i < sortedValues.size() - 1; i++) {
								            BigDecimal diff = sortedValues.get(i + 1).subtract(sortedValues.get(i)).abs();
							            	BusinessAssayProjectDataExtendRespVO preBusinessAssayProjectDataDO = vBySortedValues.get(i);
							            	BusinessAssayProjectDataExtendRespVO curBusinessAssayProjectDataDO = vBySortedValues.get(i + 1);
							            	if (i == 0) {//如果是第1个，需要把preBusinessAssayProjectDataDO放进去
							            		currentGroup.add(preBusinessAssayProjectDataDO);
											}
								            if (diff.compareTo(allowValue) > 0) {
								            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.EXCEEDS_TOLERANCE);
								            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
								            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
												preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
												curBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
								            	
								            	//存在超差，设置为待判定
								            	if (!QmsCommonConstant.ASMT_PENDING_ASSESSMENT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
									            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_ASSESSMENT);
												}
								            	
								            	// 超差：当前连续序列中断
								                // 检查之前积累的组是否有效 (长度 >= 2)
								                if (currentGroup.size() >= 2) {
								                    validGroups.add(new ArrayList<>(currentGroup)); // 保存副本
								                }
								                // 重置当前组，从当前元素重新开始
								                currentGroup.clear();
								                currentGroup.add(curBusinessAssayProjectDataDO);
								            } else {
								            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
								            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_INTERNAL_CONTROL);
								            	
								            	// 不超差：将当前元素加入正在积累的组
								                currentGroup.add(curBusinessAssayProjectDataDO);
											}
								        }
								        // 循环结束后，currentGroup 中可能还留有最后一段连续数据
								        if (currentGroup.size() >= 2) {
								            validGroups.add(new ArrayList<>(currentGroup));
								        }
								        
								        for (List<BusinessAssayProjectDataExtendRespVO> group : validGroups) {
								        	if (group.size() > val1.size()/2) {
								        		sortedValues = group.stream()
										                .map(v -> {
										                    String val = v.getValueAfter();//补正后的值
										                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
										                })
										                .sorted()
										                .collect(Collectors.toList());

										        // 计算代表值（均值或差值）
										        representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

												//计算后保留有效位数
												representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
										        //设置判定值
										        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
								            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.NORMAL);
								            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_REPORT);
								        		
										        //处理勾选
										        List<Long> collect = group.stream().map(m -> m.getId()).collect(Collectors.toList());
										        val1.forEach(item -> {
										        	if (collect.contains(item.getId())) {
										        		item.setIsNotAssessment(QmsCommonConstant.NO);
													} else {
														item.setIsNotAssessment(QmsCommonConstant.YES);
													}
								            		
								            	});
										        
												break;
											}
											
										}
								        
									} else {

										if (assayOperatorSize == 1) {//如果是单人，使用重复性。
											//过滤配置为 重复性超差
											List<ConfigAssayMethodProjectAssessmentDO> repetitivenessConfigAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentDOList.stream().filter(f -> QmsCommonConstant.ASMT_TYPE_REPETITIVENESS.equals(f.getAssessmentType())).collect(Collectors.toList());
											if (repetitivenessConfigAssayMethodProjectAssessmentDOList.size() > 0) {
												// 排序并处理 null
										        List<BigDecimal> sortedValues = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										                .map(v -> {
										                    String val = v.getValueAfter();//补正后的值
										                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
										                })
										                .sorted()
										                .collect(Collectors.toList());
										        List<BusinessAssayProjectDataExtendRespVO> vBySortedValues = val1.stream()
										        	    .filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										        	    // 构建 Entry: Key是原对象，Value是排序用的数字
										        	    .map(v -> {
										        	        String valStr = v.getValueAfter();
										        	        BigDecimal sortVal = (valStr == null || valStr.trim().isEmpty()) 
										        	                             ? BigDecimal.ZERO 
										        	                             : new BigDecimal(valStr.trim());
										        	        return new SimpleEntry<>(v, sortVal);
										        	    })
										        	    // 比较 Entry 的 Value 部分
										        	    .sorted(Map.Entry.comparingByValue())
										        	    // 提取 Key (原对象)
										        	    .map(Map.Entry::getKey)
										        	    .collect(Collectors.toList());
												
										        // 获取小数精度
										        int elementScale = businessAssayProjectDataDO.getDecimalPosition();
										        //获取有效位数
										        int effectiveDigit = businessAssayProjectDataDO.getEffectiveDigit();
										        // 计算代表值（均值或差值）
										        BigDecimal representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

												//计算后保留有效位数
												representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
										        //设置判定值
										        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
										        
										        // 查找匹配的允差规则
										        ConfigAssayMethodProjectAssessmentDO matchedRule = findMatchingRule(repetitivenessConfigAssayMethodProjectAssessmentDOList, representativeValue);
										        if (matchedRule == null) {
										            throw new ServiceException(1_032_100_000, "未找到重复性超差判定区间范围，检测项目ID: " + dictionaryProjectId + ", 值: " + representativeValue);
										        }

										        // 计算允差值
										        BigDecimal allowValue;
										        try {
										            allowValue = allowanceCalculatorComponent.calculateAllowableValue(new BigDecimal(matchedRule.getMinimumValue()), new BigDecimal(matchedRule.getMaximumValue()), new BigDecimal(matchedRule.getMinimumToleraanceValue()), new BigDecimal(matchedRule.getMaximumToleraanceValue()), new BigDecimal(matchedRule.getToleraanceAdjustmentValue()), representativeValue, matchedRule.getIsUseFormula(), matchedRule.getFormula(), elementScale);
										        } catch (Exception e) {
										            throw new ServiceException(1_032_100_000, "超差判定计算出错，检测项目ID: " + dictionaryProjectId);
										        }
										        List<List<BusinessAssayProjectDataExtendRespVO>> validGroups = new ArrayList<>();
										        List<BusinessAssayProjectDataExtendRespVO> currentGroup = new ArrayList<>();

										        // 判断相邻差值是否超差
										        for (int i = 0; i < sortedValues.size() - 1; i++) {
										            BigDecimal diff = sortedValues.get(i + 1).subtract(sortedValues.get(i)).abs();
									            	BusinessAssayProjectDataExtendRespVO preBusinessAssayProjectDataDO = vBySortedValues.get(i);
									            	BusinessAssayProjectDataExtendRespVO curBusinessAssayProjectDataDO = vBySortedValues.get(i + 1);

									            	if (i == 0) {//如果是第1个，需要把preBusinessAssayProjectDataDO放进去
									            		currentGroup.add(preBusinessAssayProjectDataDO);
													}
									            	
										            if (diff.compareTo(allowValue) > 0) {
										            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.EXCEEDS_TOLERANCE);
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
										            	int isCancelAssessment = matchedRule.getIsCancelAssessment();//查询配置，是否超差
										            	if (isCancelAssessment == 1) {
															preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.YES);
															preBusinessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.YES);
														} else {
															preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
															preBusinessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.NO);
														}
										            	
										            	//存在超差，设置为待判定
										            	if (!QmsCommonConstant.ASMT_PENDING_ASSESSMENT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
											            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_ASSESSMENT);
														}
										            	
										            	// 超差：当前连续序列中断
										                // 检查之前积累的组是否有效 (长度 >= 2)
										                if (currentGroup.size() >= 2) {
										                    validGroups.add(new ArrayList<>(currentGroup)); // 保存副本
										                }
										                // 重置当前组，从当前元素重新开始
										                currentGroup.clear();
										                currentGroup.add(curBusinessAssayProjectDataDO);
										            } else {
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPETITIVENESS);
										            	
										            	// 不超差：将当前元素加入正在积累的组
										                currentGroup.add(curBusinessAssayProjectDataDO);
													}
										        }
										        // 循环结束后，currentGroup 中可能还留有最后一段连续数据
										        if (currentGroup.size() >= 2) {
										            validGroups.add(new ArrayList<>(currentGroup));
										        }
										        
										        for (List<BusinessAssayProjectDataExtendRespVO> group : validGroups) {
										        	if (group.size() > val1.size()/2) {
										        		sortedValues = group.stream()
												                .map(v -> {
												                    String val = v.getValueAfter();//补正后的值
												                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
												                })
												                .sorted()
												                .collect(Collectors.toList());

												        // 计算代表值（均值或差值）
												        representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

														//计算后保留有效位数
														representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
												        //设置判定值
												        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
										            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.NORMAL);
										            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_REPORT);
										        		
												        //处理勾选
												        List<Long> collect = group.stream().map(m -> m.getId()).collect(Collectors.toList());
												        val1.forEach(item -> {
												        	if (collect.contains(item.getId())) {
												        		item.setIsNotAssessment(QmsCommonConstant.NO);
															} else {
																item.setIsNotAssessment(QmsCommonConstant.YES);
															}
										            		
										            	});
												        
														break;
													}
													
												}
											} else {
												throw new ServiceException(1_032_100_000, "单人,未找到重复性超差判定配置！ ");
											}
										} else {//多人使用再现性
											//再现性超差配置
											List<ConfigAssayMethodProjectAssessmentDO> reproducibilityConfigAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentDOList.stream().filter(f -> QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY.equals(f.getAssessmentType())).collect(Collectors.toList());
											if (reproducibilityConfigAssayMethodProjectAssessmentDOList.size() > 0) {
												 // 排序并处理 null
										        List<BigDecimal> sortedValues = val1.stream().filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										                .map(v -> {
										                    String val = v.getValueAfter();//补正后的值
										                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
										                })
										                .sorted()
										                .collect(Collectors.toList());
										        List<BusinessAssayProjectDataExtendRespVO> vBySortedValues = val1.stream()
										        	    .filter(f -> f.getIsCancelAssessment().equals(QmsCommonConstant.NO))
										        	    // 构建 Entry: Key是原对象，Value是排序用的数字
										        	    .map(v -> {
										        	        String valStr = v.getValueAfter();
										        	        BigDecimal sortVal = (valStr == null || valStr.trim().isEmpty()) 
										        	                             ? BigDecimal.ZERO 
										        	                             : new BigDecimal(valStr.trim());
										        	        return new SimpleEntry<>(v, sortVal);
										        	    })
										        	    // 比较 Entry 的 Value 部分
										        	    .sorted(Map.Entry.comparingByValue())
										        	    // 提取 Key (原对象)
										        	    .map(Map.Entry::getKey)
										        	    .collect(Collectors.toList());
												
										        // 获取小数精度
										        int elementScale = businessAssayProjectDataDO.getDecimalPosition();
										        //获取有效位数
										        int effectiveDigit = businessAssayProjectDataDO.getEffectiveDigit();
										        // 计算代表值（均值或差值）
										        BigDecimal representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

												//计算后保留有效位数
												representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
										        //设置判定值
										        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
										        
										        // 查找匹配的允差规则
										        ConfigAssayMethodProjectAssessmentDO matchedRule = findMatchingRule(reproducibilityConfigAssayMethodProjectAssessmentDOList, representativeValue);
										        if (matchedRule == null) {
										            throw new ServiceException(1_032_100_000, "未找到再现性超差判定区间范围，检测项目ID: " + dictionaryProjectId + ", 值: " + representativeValue);
										        }

										        // 计算允差值
										        BigDecimal allowValue;
										        try {
										            allowValue = allowanceCalculatorComponent.calculateAllowableValue(new BigDecimal(matchedRule.getMinimumValue()), new BigDecimal(matchedRule.getMaximumValue()), new BigDecimal(matchedRule.getMinimumToleraanceValue()), new BigDecimal(matchedRule.getMaximumToleraanceValue()), new BigDecimal(matchedRule.getToleraanceAdjustmentValue()), representativeValue, matchedRule.getIsUseFormula(), matchedRule.getFormula(), elementScale);
										        } catch (Exception e) {
										            throw new ServiceException(1_032_100_000, "超差判定计算出错，检测项目ID: " + dictionaryProjectId);
										        }
										        List<List<BusinessAssayProjectDataExtendRespVO>> validGroups = new ArrayList<>();
										        List<BusinessAssayProjectDataExtendRespVO> currentGroup = new ArrayList<>();

										        // 判断相邻差值是否超差
										        for (int i = 0; i < sortedValues.size() - 1; i++) {
										            BigDecimal diff = sortedValues.get(i + 1).subtract(sortedValues.get(i)).abs();
									            	BusinessAssayProjectDataExtendRespVO preBusinessAssayProjectDataDO = vBySortedValues.get(i);
									            	BusinessAssayProjectDataExtendRespVO curBusinessAssayProjectDataDO = vBySortedValues.get(i + 1);

									            	if (i == 0) {//如果是第1个，需要把preBusinessAssayProjectDataDO放进去
									            		currentGroup.add(preBusinessAssayProjectDataDO);
													}
									            	
										            if (diff.compareTo(allowValue) > 0) {
										            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.EXCEEDS_TOLERANCE);
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
														preBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
														curBusinessAssayProjectDataDO.setIsCancelAssessment(QmsCommonConstant.NO);
										            	
										            	//存在超差，设置为待判定
										            	if (!QmsCommonConstant.ASMT_PENDING_ASSESSMENT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
											            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_ASSESSMENT);
														}
										            	
										            	// 超差：当前连续序列中断
										                // 检查之前积累的组是否有效 (长度 >= 2)
										                if (currentGroup.size() >= 2) {
										                    validGroups.add(new ArrayList<>(currentGroup)); // 保存副本
										                }
										                // 重置当前组，从当前元素重新开始
										                currentGroup.clear();
										                currentGroup.add(curBusinessAssayProjectDataDO);
										            } else {
										            	preBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
										            	curBusinessAssayProjectDataDO.setAssessmentType(QmsCommonConstant.ASMT_TYPE_REPRODUCIBILITY);
										            	
										            	// 不超差：将当前元素加入正在积累的组
										                currentGroup.add(curBusinessAssayProjectDataDO);
													}
										        }
										        // 循环结束后，currentGroup 中可能还留有最后一段连续数据
										        if (currentGroup.size() >= 2) {
										            validGroups.add(new ArrayList<>(currentGroup));
										        }
										        
										        for (List<BusinessAssayProjectDataExtendRespVO> group : validGroups) {
										        	if (group.size() > val1.size()/2) {
										        		sortedValues = group.stream()
												                .map(v -> {
												                    String val = v.getValueAfter();//补正后的值
												                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
												                })
												                .sorted()
												                .collect(Collectors.toList());

												        // 计算代表值（均值或差值）
												        representativeValue = calculateRepresentativeValue(sortedValues, elementScale);

														//计算后保留有效位数
														representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
												        //设置判定值
												        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
										            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.NORMAL);
										            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_REPORT);
										        		
												        //处理勾选
												        List<Long> collect = group.stream().map(m -> m.getId()).collect(Collectors.toList());
												        val1.forEach(item -> {
												        	if (collect.contains(item.getId())) {
												        		item.setIsNotAssessment(QmsCommonConstant.NO);
															} else {
																item.setIsNotAssessment(QmsCommonConstant.YES);
															}
										            		
										            	});
												        
														break;
													}
													
												}
											} else {
												throw new ServiceException(1_032_100_000, "多人,未找到再现性超差判定配置！ ");
											}
										}
									}
								}
								
								
								
								//添加到更新列表
								updateBusinessAssayProjectDataDOList.addAll(BeanUtils.toBean(val1, BusinessAssayProjectDataDO.class));
						        
							}
							
							//如果为自动上报, 并且上报状态为待上报的
							if (QmsCommonConstant.AUTOMATIC.equals(configSubSampleMethodDO.getResultTreatmentWay()) && QmsCommonConstant.ASMT_PENDING_REPORT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
								automaticBusinessSubSampleAssessmentList.add(businessSubSampleAssessmentDO);
							}
							
							
						}
						
						
					} else if (QmsCommonConstant.ASSAY_TYPE_DOUBLE_CUP.equals(businessAssayTaskDataDO.getAssayType())) {
						
					} else {//单杯
						
						//查询判定业务
						BusinessSubSampleAssessmentDO businessSubSampleAssessmentDO = updateBusinessSubSampleAssessmentDOList.stream().filter(f -> f.getId().equals(businessAssayTaskDataDO.getBusinessSubSampleAssessmentId())).findFirst().orElse(null);
						if (businessSubSampleAssessmentDO == null) {
							businessSubSampleAssessmentDO = businessSubSampleAssessmentDOList.stream().filter(f -> f.getId().equals(businessAssayTaskDataDO.getBusinessSubSampleAssessmentId())).findFirst().orElse(null);
							updateBusinessSubSampleAssessmentDOList.add(businessSubSampleAssessmentDO);
						}
						//修改状态为待上报
		            	businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_PENDING_REPORT);
						
						//查询分析项目
						List<BusinessAssayProjectDataDO> businessAssayProjectDataDOList = businessAssayProjectDataMapper.selectList(new LambdaQueryWrapperX<BusinessAssayProjectDataDO>().in(BusinessAssayProjectDataDO::getBusinessAssayTaskDataId, businessAssayTaskDataIdList));
						
						for (BusinessAssayProjectDataDO businessAssayProjectDataDO : businessAssayProjectDataDOList) {

							//查询判定结果数据
							BusinessSubSampleAssessmentProjectDO businessSubSampleAssessmentProjectDO = businessSubSampleAssessmentProjectMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndConfigAssayMethodProjectId(businessSubSampleId, businessAssayTaskDataDO.getConfigAssayMethodId(), businessAssayProjectDataDO.getConfigAssayMethodProjectId());
							if (businessSubSampleAssessmentProjectDO == null) {
								businessSubSampleAssessmentProjectDO = new BusinessSubSampleAssessmentProjectDO();

						        saveBusinessSubSampleAssessmentProjectDOList.add(businessSubSampleAssessmentProjectDO);
							} else {
								updateBusinessSubSampleAssessmentProjectDOList.add(businessSubSampleAssessmentProjectDO);
							}
							businessSubSampleAssessmentProjectDO.setBusinessSubParentSampleId(businessAssayTaskDataDO.getBusinessSubParentSampleId());
							businessSubSampleAssessmentProjectDO.setBusinessSubSampleId(businessAssayTaskDataDO.getBusinessSubSampleId());
							businessSubSampleAssessmentProjectDO.setBusinessSubSampleAssessmentId(businessSubSampleAssessmentDO.getId());
							businessSubSampleAssessmentProjectDO.setConfigAssayMethodId(businessAssayTaskDataDO.getConfigAssayMethodId());
							businessSubSampleAssessmentProjectDO.setConfigAssayMethodProjectId(businessAssayProjectDataDO.getConfigAssayMethodProjectId());
							businessSubSampleAssessmentProjectDO.setDictionaryProjectId(businessAssayProjectDataDO.getDictionaryProjectId());
							businessSubSampleAssessmentProjectDO.setDataType(businessAssayProjectDataDO.getDataType());
							businessSubSampleAssessmentProjectDO.setDecimalPosition(businessAssayProjectDataDO.getDecimalPosition());
							businessSubSampleAssessmentProjectDO.setEffectiveDigit(businessAssayProjectDataDO.getEffectiveDigit());
							businessSubSampleAssessmentProjectDO.setAssayType(businessAssayTaskDataDO.getAssayType());
							businessSubSampleAssessmentProjectDO.setTaskType(businessAssayTaskDataDO.getTaskType());
							businessSubSampleAssessmentProjectDO.setUsage(businessAssayProjectDataDO.getUsage());
							businessSubSampleAssessmentProjectDO.setMinimumLimitValue(businessAssayProjectDataDO.getMinimumLimitValue());
							businessSubSampleAssessmentProjectDO.setSymbol(businessAssayProjectDataDO.getSymbol());
							businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.NORMAL);
							businessSubSampleAssessmentProjectDO.setAssessmentValue(businessAssayProjectDataDO.getValueAfter());//修改为赋值补正后的值
						}
						

						//如果为自动上报
						if (configSubSampleMethodDO != null && QmsCommonConstant.AUTOMATIC.equals(configSubSampleMethodDO.getResultTreatmentWay()) && QmsCommonConstant.ASMT_PENDING_REPORT.equals(businessSubSampleAssessmentDO.getReportedStatus())) {
							automaticBusinessSubSampleAssessmentList.add(businessSubSampleAssessmentDO);
						}
						
											
					}
				}
				
			}
			
			for (BusinessAssayTaskDataDO businessAssayTaskDataDO : businessAssayTaskDataDOList) {
				businessAssayTaskDataDO.setIsReported(1);
				businessAssayTaskDataDO.setReportTime(LocalDateTime.now());
				businessAssayTaskDataDO.setReporter(nickName);
			}
			
			businessAssayTaskDataMapper.updateBatch(businessAssayTaskDataDOList);
			
		} else {
			businessAssayTaskDO.setTaskAssayStatus(QmsCommonConstant.SAVED);
			businessAssayTaskDO.setFinishStatus(QmsCommonConstant.PENDING);
			businessAssayTaskDO.setFlowStatus(QmsCommonConstant.RETURNED);
		}
		businessAssayTaskMapper.updateById(businessAssayTaskDO);
		
		if (updateBusinessAssayProjectDataDOList.size() > 0) {
			businessAssayProjectDataMapper.updateBatch(updateBusinessAssayProjectDataDOList);
		}
		if (updateBusinessSubSampleAssessmentDOList.size() > 0) {
			businessSubSampleAssessmentMapper.updateBatch(updateBusinessSubSampleAssessmentDOList);
		}
		if (saveBusinessSubSampleAssessmentProjectDOList.size() > 0) {
			businessSubSampleAssessmentProjectMapper.insertBatch(saveBusinessSubSampleAssessmentProjectDOList);
		}
		if (updateBusinessSubSampleAssessmentProjectDOList.size() > 0) {
			businessSubSampleAssessmentProjectMapper.updateBatch(updateBusinessSubSampleAssessmentProjectDOList);
		}
		
		//执行自动上报
		if (automaticBusinessSubSampleAssessmentList.size() > 0) {
			for (BusinessSubSampleAssessmentDO automaticBusinessSubSampleAssessment : automaticBusinessSubSampleAssessmentList) {
				this.assessmentDataReporting(automaticBusinessSubSampleAssessment.getBusinessSubSampleId(), automaticBusinessSubSampleAssessment.getConfigAssayMethodId(), automaticBusinessSubSampleAssessment.getRetestCount());
			}
		}
		
	}
	
	// 查找匹配的允差区间
	private ConfigAssayMethodProjectAssessmentDO findMatchingRule(List<ConfigAssayMethodProjectAssessmentDO> rules, BigDecimal value) {
	    if (rules == null || rules.isEmpty()) return null;
	    
	    // 特殊处理 level=0 和 level=4
	    for (ConfigAssayMethodProjectAssessmentDO rule : rules) {
	        if (rule.getAssessmentLevel() == 0) {
	        	ConfigAssayMethodProjectAssessmentDO next = rules.stream()
	                    .filter(r -> r.getAssessmentLevel() == 1)
	                    .findFirst()
	                    .orElse(rule);
	            if (value.compareTo(new BigDecimal(rule.getMinimumValue())) >= 0 && value.compareTo(new BigDecimal(rule.getMaximumValue())) <= 0) {
	                return next;
	            }
	        } else if (rule.getAssessmentLevel() == 4) {
	        	ConfigAssayMethodProjectAssessmentDO prev = rules.stream()
	                    .filter(r -> r.getAssessmentLevel() == 3)
	                    .findFirst()
	                    .orElse(rule);
	            if (value.compareTo(new BigDecimal(rule.getMinimumValue())) >= 0 && value.compareTo(new BigDecimal(rule.getMaximumValue())) <= 0) {
	                return prev;
	            }
	        } else {
	            if (value.compareTo(new BigDecimal(rule.getMinimumValue())) >= 0 && value.compareTo(new BigDecimal(rule.getMaximumValue())) <= 0) {
	                return rule;
	            }
	        }
	    }
	    return null;
	}

	// 计算代表值：1个取本身，2个取均值，>2取平均
	private BigDecimal calculateRepresentativeValue(List<BigDecimal> values, int elementScale) {
	    int size = values.size();
	    if (size == 0) return BigDecimal.ZERO;
	    if (size == 1) return values.get(0).setScale(elementScale, RoundingMode.HALF_EVEN);
	    if (size == 2) {
	        return values.get(0).add(values.get(1)).divide(BigDecimal.valueOf(2), elementScale, RoundingMode.HALF_EVEN);
	    }
	    BigDecimal sum = values.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
	    return sum.divide(BigDecimal.valueOf(size), elementScale, RoundingMode.HALF_EVEN);
	}

	@Resource
	private ConfigSampleReportMapper configSampleReportMapper;
	
	@Resource
	private ConfigReportFieldMapper configReportFieldMapper;
	
	@Resource
	private ConfigReportTypeMapper configReportTypeMapper;
	
	@Resource
	private ConfigProjectMapper configProjectMapper;
	
	@Resource
	private BusinessAssayReportDataMapper businessAssayReportDataMapper;
	
	@Resource
	private BusinessBaseSampleMapper businessBaseSampleMapper;
	
	@Resource
	private ConfigSubSampleParentMethodMapper configSubSampleParentMethodMapper;
	
	@Resource
	private BusinessSubParentSampleMapper businessSubParentSampleMapper;
	
	@Resource
	private BusinessSubParentSampleAssessmentMapper businessSubParentSampleAssessmentMapper;
	
	@Resource
	private BusinessSubParentSampleAssessmentProjectMapper businessSubParentSampleAssessmentProjectMapper;
	
	@Resource
	private SampleResultReportingService sampleResultReportingService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void assessmentDataReporting(Long businessSubSampleId, Long configAssayMethodId, Integer retestCount) {
		//当前登录用户昵称
		String nickName = SecurityFrameworkUtils.getLoginUserNickname();
		List<BusinessAssayTaskDataDO> unReportedList = businessAssayTaskDataMapper.selectIsReportedList(null, businessSubSampleId, configAssayMethodId, retestCount, QmsCommonConstant.NO);
		if (unReportedList.size() > 0) {
			throw new ServiceException(1_032_100_000, "存在未上报的数据");
		}
		//自动上报
		List<BusinessSubParentSampleIdAndRetestCount> automaticBusinessSubParentSampleIdAndRetestCounts = new ArrayList<>();
		
		List<BusinessSubParentSampleAssessmentProjectDO> businessSubParentSampleAssessmentDOList = new ArrayList<>();
		
		//分析任务已全部上报
		List<BusinessAssayTaskDataDO> reportedList = businessAssayTaskDataMapper.selectIsReportedList(null, businessSubSampleId, configAssayMethodId, retestCount, QmsCommonConstant.YES);
		//判定结果
		List<BusinessSubSampleAssessmentProjectExtendRespVO> businessSubSampleAssessmentList = businessSubSampleAssessmentProjectMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndRetestCount(businessSubSampleId, configAssayMethodId, retestCount);
		
		List<Long> businessSubSampleAssessmentIdList = businessSubSampleAssessmentList.stream().map(m -> m.getId()).collect(Collectors.toList());
		
		BusinessAssayTaskDataDO businessAssayTaskDataDO = reportedList.get(0);
		
		//查询主样
		//BusinessBaseSampleDO businessBaseSampleDO = businessBaseSampleMapper.selectById(businessAssayTaskDataDO.getBusinessBaseSampleId());

		//查询分样
		BusinessSubParentSampleDO businessSubParentSampleDO = businessSubParentSampleMapper.selectById(businessAssayTaskDataDO.getBusinessSubParentSampleId());
		
		//查询分样对应的方法
		ConfigSubSampleParentMethodDO configSubSampleParentMethodDO = configSubSampleParentMethodMapper.selectByConfigSubSampleParentIdAndConfigAssayMethodId(businessSubParentSampleDO.getConfigSubSampleParentId(), configAssayMethodId);
		
		//子样判定
		BusinessSubSampleAssessmentDO businessSubSampleAssessmentDO = businessSubSampleAssessmentMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndRetestCount(businessSubSampleId, configAssayMethodId, retestCount);
		
		//分样判定
		BusinessSubParentSampleAssessmentDO businessSubParentSampleAssessmentDO = businessSubParentSampleAssessmentMapper.selectByBusinessSubParentSampleIdAndConfigAssayMethodIdAndRetestCount(businessSubParentSampleDO.getId(), configAssayMethodId, retestCount);
		
		//循环判定值
		BusinessSubParentSampleAssessmentProjectDO businessSubParentSampleAssessmentProjectDO = null;
		for (BusinessSubSampleAssessmentProjectExtendRespVO businessSubSampleAssessment : businessSubSampleAssessmentList) {
			businessSubParentSampleAssessmentProjectDO = new BusinessSubParentSampleAssessmentProjectDO();
			businessSubParentSampleAssessmentProjectDO.setBusinessSubParentSampleAssessmentId(businessSubParentSampleAssessmentDO.getId());
			businessSubParentSampleAssessmentProjectDO.setBusinessSubParentSampleId(businessAssayTaskDataDO.getBusinessSubParentSampleId());
			businessSubParentSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.NORMAL);
			businessSubParentSampleAssessmentProjectDO.setAssessmentValue(businessSubSampleAssessment.getAssessmentValue());
			businessSubParentSampleAssessmentProjectDO.setSymbol(businessSubSampleAssessment.getSymbol());
			businessSubParentSampleAssessmentProjectDO.setTaskType(businessSubSampleAssessment.getTaskType());
			businessSubParentSampleAssessmentProjectDO.setAssayType(businessSubSampleAssessment.getAssayType());
			businessSubParentSampleAssessmentProjectDO.setDataType(businessSubSampleAssessment.getDataType());
			businessSubParentSampleAssessmentProjectDO.setDecimalPosition(businessSubSampleAssessment.getDecimalPosition());
			businessSubParentSampleAssessmentProjectDO.setEffectiveDigit(businessSubSampleAssessment.getEffectiveDigit());
			businessSubParentSampleAssessmentProjectDO.setUsage(businessSubSampleAssessment.getUsage());
			businessSubParentSampleAssessmentProjectDO.setMinimumLimitValue(businessSubParentSampleAssessmentProjectDO.getMinimumLimitValue());
			businessSubParentSampleAssessmentProjectDO.setConfigAssayMethodId(businessSubSampleAssessment.getConfigAssayMethodId());
			businessSubParentSampleAssessmentProjectDO.setConfigAssayMethodProjectId(businessSubSampleAssessment.getConfigAssayMethodProjectId());
			businessSubParentSampleAssessmentProjectDO.setDictionaryProjectId(businessSubSampleAssessment.getDictionaryProjectId());
			
			businessSubParentSampleAssessmentDOList.add(businessSubParentSampleAssessmentProjectDO);
		}
		
		
		if (businessSubParentSampleAssessmentDOList.size() > 0) {
			businessSubParentSampleAssessmentProjectMapper.insertBatch(businessSubParentSampleAssessmentDOList);
		}
		
		//修改子样判定为已上报
		businessSubSampleAssessmentDO.setIsReported(QmsCommonConstant.YES);
		businessSubSampleAssessmentDO.setReporter(nickName);
		businessSubSampleAssessmentDO.setReportTime(LocalDateTime.now());
		businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_REPORTED);
		
		businessSubSampleAssessmentMapper.updateById(businessSubSampleAssessmentDO);
		
		businessSubSampleAssessmentProjectMapper.update(new LambdaUpdateWrapper<BusinessSubSampleAssessmentProjectDO>()
				.set(BusinessSubSampleAssessmentProjectDO::getIsReported, QmsCommonConstant.YES)
				.set(BusinessSubSampleAssessmentProjectDO::getReporter, nickName)
				.set(BusinessSubSampleAssessmentProjectDO::getReportTime, LocalDateTime.now())
				.in(BusinessSubSampleAssessmentProjectDO::getId, businessSubSampleAssessmentIdList));
		
		if (configSubSampleParentMethodDO != null && QmsCommonConstant.AUTOMATIC.equals(configSubSampleParentMethodDO.getResultTreatmentWay())) {
			automaticBusinessSubParentSampleIdAndRetestCounts.add(new BusinessSubParentSampleIdAndRetestCount(businessSubParentSampleDO.getId(), retestCount));
			BatchResultDataReportingReqVO batchResultDataReportingReqVO = new BatchResultDataReportingReqVO();
			batchResultDataReportingReqVO.setBusinessSubParentSampleIdAndRetestCounts(automaticBusinessSubParentSampleIdAndRetestCounts);
			batchResultDataReportingReqVO.setConfigAssayMethodId(configAssayMethodId);
			
			sampleResultReportingService.batchResultDataReporting(batchResultDataReportingReqVO);
		}
	}

	@Resource
	private ConfigSubSampleMapper configSubSampleMapper;
	
	@Resource
	private ConfigAssayMethodParameterMapper configAssayMethodParameterMapper;
	
	@Resource
	private BusinessSubSampleMapper businessSubSampleMapper;
	
	@Resource
	private BusinessAssayParameterDataMapper businessAssayParameterDataMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createReAnalysis(Long businessSubSampleId, Long configAssayMethodId, Integer retestCount, Integer taskCount) {
		//子样数据
		BusinessSubSampleDO businessSubSampleDO = businessSubSampleMapper.selectById(businessSubSampleId);
		
		//子样配置数据
		ConfigSubSampleDO configSubSampleDO = configSubSampleMapper.selectById(businessSubSampleDO.getConfigSubSampleId());
		if (StringUtils.isBlank(configSubSampleDO.getRecheckFlowNodeKey())) {
			throw new ServiceException(1_032_100_000, "未配置复检流程，不能发起复检委托！");
		}
		
		//查询当前子样方法配置
		ConfigSubSampleMethodExtendRespVO configSubSampleMethod = configSubSampleMethodMapper.selectByConfigSubSampleIdAndConfigAssayMethodId(businessSubSampleDO.getConfigSubSampleId(), configAssayMethodId);
		//扩展配置
    	String configInfomation = configSubSampleMethod.getConfigInfomation();
		List<ConfigSubSampleMethodConfItem> getParamList = null;
    	if (StringUtils.isNotBlank(configInfomation)) {
    		//解析配置
			ConfigSubSampleMethodConfInfo configSubSampleMethodConfInfo = JSON.parseObject(configInfomation, ConfigSubSampleMethodConfInfo.class);
			getParamList = configSubSampleMethodConfInfo.getGetParam();
		}
    	
		
		List<BusinessAssayTaskDataDO> newBusinessAssayTaskDataDOList = new ArrayList<>();
		List<BusinessAssayTaskParameterDataDO> newBusinessAssayTaskParameterDataDOList = new ArrayList<>();
		List<BusinessAssayProjectDataDO> newBusinessAssayProjectDataDOList = new ArrayList<>();
		List<BusinessAssayParameterDataDO> newBusinessAssayParameterDataDOList  = new ArrayList<>();
		
		//查询当前子样判定
		BusinessSubSampleAssessmentDO businessSubSampleAssessmentDO = businessSubSampleAssessmentMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndRetestCount(businessSubSampleId, configAssayMethodId, retestCount);

		BusinessAssayTaskDataDO newBusinessAssayTaskDataDO = null;
		//查询分析任务列表
		List<BusinessAssayTaskDataDO> businessAssayTaskDataDOList = businessAssayTaskDataMapper.selectMaxRecheckCountByBusinessSubSampleIdAndConfigAssayMethodId(businessSubSampleId,	configAssayMethodId);
		//查询分析任务Id列表
		List<Long> businessAssayTaskDataDOIdList = businessAssayTaskDataDOList.stream().map(m -> m.getId()).collect(Collectors.toList());
		//查询分析任务属性
		List<BusinessAssayTaskParameterDataExtendRespVO> businessAssayTaskParameterDataList = businessAssayTaskParameterDataMapper.selectExtendByBusinessAssayTaskDataIds(businessAssayTaskDataDOIdList);
		//查询检测项目
		List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataDOList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(businessAssayTaskDataDOIdList);
		//查询检测项目id列表
		List<Long> businessAssayProjectDataDOIdList = businessAssayProjectDataDOList.stream().map(m -> m.getId()).collect(Collectors.toList());
		//查询检测项目参数列表
		List<BusinessAssayParameterDataExtendRespVO> businessAssayParameterDataDOList = new ArrayList<>();
		if (CollUtil.isNotEmpty(businessAssayProjectDataDOIdList)) {
			businessAssayParameterDataDOList = businessAssayParameterDataMapper.selectExtendByBusinessAssayProjectDataIds(businessAssayProjectDataDOIdList);
		}
		//查询检测项目参数配置id列表
		List<Long> configAssayMethodProjectParameterIdList = businessAssayParameterDataDOList.stream().map(m -> m.getConfigAssayMethodProjectParameterId()).distinct().collect(Collectors.toList());
		List<ConfigAssayMethodProjectParameterDO> configAssayMethodProjectParameterList = new ArrayList<>();
		//查询检测项目参数配置列表
		if (CollUtil.isNotEmpty(configAssayMethodProjectParameterIdList)) {
			configAssayMethodProjectParameterList = configAssayMethodProjectParameterMapper.selectByIds(configAssayMethodProjectParameterIdList);
		}
		int localTaskCount = 0;
		//循环检测任务
		for (BusinessAssayTaskDataDO businessAssayTaskDataDO : businessAssayTaskDataDOList) {
			localTaskCount++;//循环+1
			if (localTaskCount > taskCount) {//本地数据大于，则跳出循环
				break;
			}
			
			// 子样检测任务
			newBusinessAssayTaskDataDO = new BusinessAssayTaskDataDO();
			newBusinessAssayTaskDataDO.setId(IdWorker.getId());
			newBusinessAssayTaskDataDO.setBusinessBaseSampleId(businessAssayTaskDataDO.getBusinessBaseSampleId());
			newBusinessAssayTaskDataDO.setBusinessSubParentSampleId(businessAssayTaskDataDO.getBusinessSubParentSampleId());
			newBusinessAssayTaskDataDO.setBusinessSubSampleId(businessAssayTaskDataDO.getBusinessSubSampleId());
			newBusinessAssayTaskDataDO.setConfigAssayMethodId(businessAssayTaskDataDO.getConfigAssayMethodId());
			newBusinessAssayTaskDataDO.setBusinessSubSampleAssessmentId(businessSubSampleAssessmentDO.getId());
			newBusinessAssayTaskDataDO.setAssayType(businessAssayTaskDataDO.getAssayType());
			newBusinessAssayTaskDataDO.setTaskType(businessAssayTaskDataDO.getTaskType());
			newBusinessAssayTaskDataDO.setConfigSampleFlowId(businessAssayTaskDataDO.getConfigSampleFlowId());
			newBusinessAssayTaskDataDO.setSampleFlowNodeKey(configSubSampleDO.getRecheckFlowNodeKey());
			newBusinessAssayTaskDataDO.setSampleFlowNodeTime(LocalDateTime.now());
			newBusinessAssayTaskDataDO.setAssayDepartmentId(businessAssayTaskDataDO.getAssayDepartmentId());
			newBusinessAssayTaskDataDO.setAssayDepartmentName(businessAssayTaskDataDO.getAssayDepartmentName());
			newBusinessAssayTaskDataDO.setRecheckCount(businessAssayTaskDataDO.getRecheckCount() + 1);
			newBusinessAssayTaskDataDO.setRetestCount(businessAssayTaskDataDO.getRetestCount());
			newBusinessAssayTaskDataDO.setAssayProject(businessAssayTaskDataDO.getAssayProject());
			
			//分析任务属性
			List<BusinessAssayTaskParameterDataExtendRespVO> currentBusinessAssayTaskParameterDataList = businessAssayTaskParameterDataList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskDataDO.getId())).collect(Collectors.toList());
			for (BusinessAssayTaskParameterDataExtendRespVO currentBusinessAssayTaskParameterData : currentBusinessAssayTaskParameterDataList) {
				BusinessAssayTaskParameterDataDO businessAssayTaskParameterDataDO = new BusinessAssayTaskParameterDataDO();
				businessAssayTaskParameterDataDO.setId(IdWorker.getId());
				businessAssayTaskParameterDataDO.setBusinessAssayTaskDataId(newBusinessAssayTaskDataDO.getId());
				businessAssayTaskParameterDataDO.setConfigAssayMethodParameterId(currentBusinessAssayTaskParameterData.getConfigAssayMethodParameterId());
				businessAssayTaskParameterDataDO.setDataType(currentBusinessAssayTaskParameterData.getDataType());
				businessAssayTaskParameterDataDO.setDecimalPosition(currentBusinessAssayTaskParameterData.getDecimalPosition());
				
				ConfigAssayMethodParameterDO configAssayMethodParameterDO = configAssayMethodParameterMapper.selectById(currentBusinessAssayTaskParameterData.getConfigAssayMethodParameterId());
				
				if (configAssayMethodParameterDO != null && StringUtils.isNotBlank(configAssayMethodParameterDO.getDefaultValue())) {
					businessAssayTaskParameterDataDO.setValue(configAssayMethodParameterDO.getDefaultValue());
				}
				if (getParamList != null) {
					ConfigSubSampleMethodConfItem targetAttribute = getParamList.stream().filter(f -> StringUtils.isNotBlank(f.getTarget().getAttribute()) && f.getTarget().getAttribute().equals(currentBusinessAssayTaskParameterData.getKey())).findFirst().orElse(null);
					if (targetAttribute != null) {
						businessAssayTaskParameterDataDO.setValue(currentBusinessAssayTaskParameterData.getValue());
					}
				}
				
				newBusinessAssayTaskParameterDataDOList.add(businessAssayTaskParameterDataDO);
			}
			
			List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataList = businessAssayProjectDataDOList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskDataDO.getId())).collect(Collectors.toList());
			for (BusinessAssayProjectDataExtendRespVO businessAssayProjectData : businessAssayProjectDataList) {
				//检测项目
				BusinessAssayProjectDataDO businessAssayProjectDataDO = new BusinessAssayProjectDataDO();
				businessAssayProjectDataDO.setId(IdWorker.getId());
				businessAssayProjectDataDO.setBusinessAssayTaskDataId(newBusinessAssayTaskDataDO.getId());
				businessAssayProjectDataDO.setConfigAssayMethodProjectId(businessAssayProjectData.getConfigAssayMethodProjectId());
				businessAssayProjectDataDO.setDictionaryProjectId(businessAssayProjectData.getDictionaryProjectId());
				businessAssayProjectDataDO.setDataType(businessAssayProjectData.getDataType());
				businessAssayProjectDataDO.setDecimalPosition(businessAssayProjectData.getDecimalPosition());
				businessAssayProjectDataDO.setEffectiveDigit(businessAssayProjectData.getEffectiveDigit());
				businessAssayProjectDataDO.setIsEnabled(businessAssayProjectData.getIsEnabled());
				businessAssayProjectDataDO.setIsNotAssessment(0);
				
				newBusinessAssayProjectDataDOList.add(businessAssayProjectDataDO);
				
				List<BusinessAssayParameterDataExtendRespVO> businessAssayParameterDataList = businessAssayParameterDataDOList.stream().filter(f -> f.getBusinessAssayProjectDataId().equals(businessAssayProjectData.getId())).collect(Collectors.toList());
				for (BusinessAssayParameterDataExtendRespVO businessAssayParameterData : businessAssayParameterDataList) {
					
					ConfigAssayMethodProjectParameterDO configAssayMethodProjectParameter = configAssayMethodProjectParameterList.stream().filter(f -> businessAssayParameterData.getConfigAssayMethodProjectParameterId().equals(f.getId())).findFirst().orElse(null);
					
					BusinessAssayParameterDataDO businessAssayParameterDataDO = new BusinessAssayParameterDataDO();
					businessAssayParameterDataDO.setId(IdWorker.getId());
					businessAssayParameterDataDO.setBusinessAssayProjectDataId(businessAssayProjectDataDO.getId());
					businessAssayParameterDataDO.setConfigAssayMethodProjectParameterId(businessAssayParameterData.getConfigAssayMethodProjectParameterId());
					businessAssayParameterDataDO.setDictionaryParameterId(businessAssayParameterData.getDictionaryParameterId());
					businessAssayParameterDataDO.setDataType(businessAssayParameterData.getDataType());
					businessAssayParameterDataDO.setDecimalPosition(businessAssayParameterData.getDecimalPosition());
					
					if (StringUtils.isNotBlank(configAssayMethodProjectParameter.getDefaultValue())) {
						businessAssayParameterDataDO.setValue(configAssayMethodProjectParameter.getDefaultValue());
					}
					
					if (getParamList != null) {
						List<String> targetParameterList = getParamList.stream().filter(f -> StringUtils.isNotBlank(f.getTarget().getProject()) && f.getTarget().getProject().contains(businessAssayProjectData.getSimpleName())).map(m -> m.getTarget().getParameter()).collect(Collectors.toList());
						if (StringUtils.isNotBlank(businessAssayParameterData.getParameterKey()) && CollUtil.isNotEmpty(targetParameterList) && targetParameterList.contains(businessAssayParameterData.getParameterKey())) {
					    	businessAssayParameterDataDO.setValue(businessAssayParameterData.getValue());
						}
					}
					
					newBusinessAssayParameterDataDOList.add(businessAssayParameterDataDO);
				}
			}
			
			newBusinessAssayTaskDataDOList.add(newBusinessAssayTaskDataDO);
			
		}
		
		//修改判定状态
		//查询判定值
		List<BusinessSubSampleAssessmentProjectExtendRespVO> businessSubSampleAssessmentList = businessSubSampleAssessmentProjectMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndRetestCount(businessSubSampleId, configAssayMethodId, retestCount);
		for (BusinessSubSampleAssessmentProjectExtendRespVO businessSubSampleAssessmentProjectExtendRespVO : businessSubSampleAssessmentList) {
			businessSubSampleAssessmentProjectExtendRespVO.setAssessmentValue(null);
			businessSubSampleAssessmentProjectExtendRespVO.setAssessmentStatus(QmsCommonConstant.IN_PROGRESS);
		}
		//修改上报状态为复测中
		businessSubSampleAssessmentDO.setReportedStatus(QmsCommonConstant.ASMT_RE_INSPECTED);
		
		businessSubSampleAssessmentMapper.updateById(businessSubSampleAssessmentDO);
		
		if (newBusinessAssayTaskDataDOList.size() > 0) {
			businessAssayTaskDataMapper.insertBatch(newBusinessAssayTaskDataDOList);
		}
		if (newBusinessAssayTaskParameterDataDOList.size() > 0) {
			businessAssayTaskParameterDataMapper.insertBatch(newBusinessAssayTaskParameterDataDOList);
		}
		if (newBusinessAssayProjectDataDOList.size() > 0) {
			businessAssayProjectDataMapper.insertBatch(newBusinessAssayProjectDataDOList);
		}
		if (newBusinessAssayParameterDataDOList.size() > 0) {
			businessAssayParameterDataMapper.insertBatch(newBusinessAssayParameterDataDOList);
		}
		if (businessSubSampleAssessmentList.size() > 0) {
			List<BusinessSubSampleAssessmentProjectDO> businessSubSampleAssessmentDOList = BeanUtil.copyToList(businessSubSampleAssessmentList, BusinessSubSampleAssessmentProjectDO.class);
			businessSubSampleAssessmentProjectMapper.updateBatch(businessSubSampleAssessmentDOList);
		}
		
	}

	@Resource
	private ConfigRuleMapper configRuleMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public JSONObject modifyParallelResultAssessment(Long businessSubSampleId, Long configAssayMethodId, Long businessSubSampleAssessmentId, List<Long> businessAssayProjectDataIds) {
		BusinessSubSampleAssessmentProjectDO businessSubSampleAssessmentProjectDO = businessSubSampleAssessmentProjectMapper.selectById(businessSubSampleAssessmentId);
		//查询子样
		BusinessSubSampleDO businessSubSampleDO = businessSubSampleMapper.selectById(businessSubSampleId);
		//查询子样与方法的配置
		ConfigSubSampleMethodExtendRespVO configSubSampleMethodDO = configSubSampleMethodMapper.selectByConfigSubSampleIdAndConfigAssayMethodId(businessSubSampleDO.getConfigSubSampleId(), configAssayMethodId);
		
		//计算判定值计算规则
		ConfigRuleDO calculateAssessmentValue = configRuleMapper.selectLatestConfigRuleByCode(configSubSampleMethodDO.getCalculateMethod());
		
		BusinessAssayProjectDataReqVO businessAssayProjectDataSearch = new BusinessAssayProjectDataReqVO();
		businessAssayProjectDataSearch.setBusinessSubSampleId(businessSubSampleId);
		businessAssayProjectDataSearch.setConfigAssayMethodId(configAssayMethodId);
		businessAssayProjectDataSearch.setConfigAssayMethodProjectId(businessSubSampleAssessmentProjectDO.getConfigAssayMethodProjectId());
		List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataList = businessAssayProjectDataMapper.selectAnalysisBy(businessAssayProjectDataSearch);
		List<BusinessAssayProjectDataDO> businessAssayProjectDataDOList = BeanUtil.copyToList(businessAssayProjectDataList, BusinessAssayProjectDataDO.class);
		for (BusinessAssayProjectDataDO businessAssayProjectDataDO : businessAssayProjectDataDOList) {
			if (businessAssayProjectDataIds.contains(businessAssayProjectDataDO.getId())) {
				businessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.NO);
			} else {
				businessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.YES);
			}
		}
		// 排序并处理 null
        List<BigDecimal> sortedValues = businessAssayProjectDataDOList.stream()
        		.filter(f -> f.getIsNotAssessment().equals(QmsCommonConstant.NO))
                .map(v -> {
                    String val = v.getValueAfter();//设置为补正后的
                    return val == null || val.trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(val.trim());
                })
                .sorted()
                .collect(Collectors.toList());
        
        //符号处理
        String symbol = "=";
        BusinessAssayProjectDataDO noEquals = businessAssayProjectDataDOList.stream().filter(f -> !"=".equals(f.getSymbol())).findFirst().orElse(null);
        if (noEquals != null) {
			symbol = noEquals.getSymbol();
		}
        businessSubSampleAssessmentProjectDO.setSymbol(symbol);
		
        // 获取小数精度
        int elementScale = businessSubSampleAssessmentProjectDO.getDecimalPosition();
        // 获取有效位数
        int effectiveDigit = businessSubSampleAssessmentProjectDO.getEffectiveDigit();
        // 计算代表值（均值\）
//        BigDecimal representativeValue = calculateRepresentativeValue(sortedValues, elementScale);
        Map<String, Object> context = new HashMap<>();
        context.put("values", sortedValues);
        context.put("scale", elementScale);
        BigDecimal representativeValue = null;
		try {
			//representativeValue = (BigDecimal) expressRunner.execute(calculateAssessmentValue.getExpression(), context, null, false, false);
			QLResult expressResult = express4Runner.execute(calculateAssessmentValue.getExpression(), context, QLOptions.builder().precise(true).build());//高精度计算
			representativeValue = (BigDecimal) expressResult.getResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//计算后保留有效位数
		representativeValue = EffectiveNumberFormatter.formatNumber2(representativeValue, elementScale, effectiveDigit);
        //设置判定值
        businessSubSampleAssessmentProjectDO.setAssessmentValue(representativeValue.toPlainString());
        
//		List<ConfigAssayMethodProjectAssessmentDO> configAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentMapper.selectList(new LambdaQueryWrapperX<ConfigAssayMethodProjectAssessmentDO>()
//				.eq(ConfigAssayMethodProjectAssessmentDO::getConfigAssayMethodId, businessSubSampleAssessmentProjectDO.getConfigAssayMethodId())
//				.eq(ConfigAssayMethodProjectAssessmentDO::getConfigAssayMethodProjectId, businessSubSampleAssessmentProjectDO.getConfigAssayMethodProjectId()));
        List<ConfigAssayMethodProjectAssessmentDO> configAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentMapper.selectByConfigBaseSampleIdAndConfigAssayMethodIdAndConfigAssayMethodProjectId(configSubSampleMethodDO.getConfigBaseSampleId(), businessSubSampleAssessmentProjectDO.getConfigAssayMethodId(), businessSubSampleAssessmentProjectDO.getConfigAssayMethodProjectId());
        List<ConfigAssayMethodProjectAssessmentDO> assessmentTypeConfigAssayMethodProjectAssessmentDOList = configAssayMethodProjectAssessmentDOList.stream().filter(f -> businessAssayProjectDataDOList.get(0).getAssessmentType().equals(f.getAssessmentType())).collect(Collectors.toList());
        
        // 查找匹配的允差规则
        ConfigAssayMethodProjectAssessmentDO matchedRule = findMatchingRule(assessmentTypeConfigAssayMethodProjectAssessmentDOList, representativeValue);
        if (matchedRule == null) {
            throw new ServiceException(1_032_100_000, "未找到超差判定区间范围，元素ID: " + businessSubSampleAssessmentProjectDO.getDictionaryProjectId() + ", 值: " + representativeValue);
        }

        // 计算允差值
        BigDecimal allowValue;
        try {
            allowValue = allowanceCalculatorComponent.calculateAllowableValue(new BigDecimal(matchedRule.getMinimumValue()), new BigDecimal(matchedRule.getMaximumValue()), new BigDecimal(matchedRule.getMinimumToleraanceValue()), new BigDecimal(matchedRule.getMaximumToleraanceValue()), new BigDecimal(matchedRule.getToleraanceAdjustmentValue()), representativeValue, matchedRule.getIsUseFormula(), matchedRule.getFormula(), elementScale);
        } catch (Exception e) {
            throw new ServiceException(1_032_100_000, "超差判定计算出错，检测项目ID: " + businessSubSampleAssessmentProjectDO.getDictionaryProjectId());
        }

    	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.NORMAL);
        // 判断相邻差值是否超差
        for (int i = 0; i < sortedValues.size() - 1; i++) {
            BigDecimal diff = sortedValues.get(i + 1).subtract(sortedValues.get(i)).abs();
            if (diff.compareTo(allowValue) > 0) {
            	businessSubSampleAssessmentProjectDO.setAssessmentStatus(QmsCommonConstant.EXCEEDS_TOLERANCE);
            	break;
            }
        }
		
        //更新判定值
        businessSubSampleAssessmentProjectMapper.updateById(businessSubSampleAssessmentProjectDO);
        //更新检测项目
        businessAssayProjectDataMapper.updateBatch(businessAssayProjectDataDOList);
		
		
		return getParallelResultAssessment(businessSubSampleId, configAssayMethodId);
	}

	


	
}
