package com.zt.plat.module.qms.business.bus.liteflow.sample.taskassign;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.module.qms.business.bus.controller.vo.BusinessAssayProjectDataExtendRespVO;
import com.zt.plat.module.qms.business.bus.controller.vo.BusinessAssayTaskParameterDataExtendRespVO;
import com.zt.plat.module.qms.business.bus.controller.vo.BusinessSubParentSampleAssessmentExtendRespVO;
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.BusinessAssayReportDataDO;
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.BusinessSubParentSampleAssessmentDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleAssessmentDO;
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.BusinessAssayTaskDataMapper;
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.BusinessSubParentSampleAssessmentMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleAssessmentMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleMapper;
import com.zt.plat.module.qms.business.bus.liteflow.param.AssignAssayUser;
import com.zt.plat.module.qms.business.bus.liteflow.slot.SampleTaskAssignContext;
import com.zt.plat.module.qms.business.bus.liteflow.slot.SampleTaskAssignTypeEnum;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigAssayMethodProjectExtendRespVO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigAssayMethodDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigAssayMethodParameterDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigAssayMethodProjectParameterDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigReportTemplateDO;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodParameterMapper;
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.ConfigReportTemplateMapper;
import com.zt.plat.module.qms.common.dic.dal.dataobject.DictionaryBusinessDO;
import com.zt.plat.module.qms.common.dic.dal.mapper.DictionaryBusinessMapper;
import com.zt.plat.module.qms.core.code.SequenceUtil;
import com.zt.plat.module.qms.enums.QmsCommonConstant;

import cn.hutool.core.collection.CollUtil;
import jakarta.annotation.Resource;

@LiteflowComponent(id = "sampleTaskAssignProjectMethodCmp", name = "手动分配(按检测项目已指定方法分配)")
public class SampleTaskAssignProjectMethodCmp extends NodeComponent {

	@Resource
	private SequenceUtil sequenceUtil;
	
	@Resource
	private DictionaryBusinessMapper dictionaryBusinessMapper;
	
	@Resource
	private ConfigAssayMethodMapper configAssayMethodMapper;
	
	@Resource
	private ConfigAssayMethodParameterMapper configAssayMethodParameterMapper;
	
	@Resource
	private ConfigAssayMethodProjectMapper configAssayMethodProjectMapper;
	
	@Resource
	private ConfigAssayMethodProjectParameterMapper configAssayMethodProjectParameterMapper;
	
	@Resource
	private ConfigReportTemplateMapper configReportTemplateMapper;
	
	@Resource
	private BusinessAssayTaskMapper businessAssayTaskMapper;
	
	@Resource
	private BusinessAssayTaskDataMapper businessAssayTaskDataMapper;
	
	@Resource
	private BusinessAssayTaskParameterDataMapper businessAssayTaskParameterDataMapper;
	
	@Resource
	private BusinessAssayProjectDataMapper businessAssayProjectDataMapper;
	
	@Resource
	private BusinessAssayParameterDataMapper businessAssayParameterDataMapper;
	
	@Resource
	private BusinessSubSampleMapper businessSubSampleMapper;
	
	@Resource
	private BusinessSubSampleAssessmentMapper businessSubSampleAssessmentMapper;
	
	@Resource
	private BusinessSubParentSampleAssessmentMapper businessSubParentSampleAssessmentMapper;

	@Override
	public void process() throws Exception {
		SampleTaskAssignContext sampleTaskAssignContext = this.getContextBean(SampleTaskAssignContext.class);
		String loginRealname = sampleTaskAssignContext.getLoginRealname();
		LoginUser loginUser = sampleTaskAssignContext.getLoginUser();
		LocalDateTime currentDateTime = sampleTaskAssignContext.getCurrentDateTime();
		//指派的方法
		Long assignConfigAssayMethodId = sampleTaskAssignContext.getAssignConfigAssayMethodId();
		ConfigAssayMethodDO configAssayMethodDO = configAssayMethodMapper.selectById(assignConfigAssayMethodId);
		//方法类型id
		Long dictionaryBusinessId = configAssayMethodDO.getDictionaryBusinessId();
		DictionaryBusinessDO dictionaryBusinessDO = dictionaryBusinessMapper.selectById(dictionaryBusinessId);
		//查询报表模板
		ConfigReportTemplateDO configReportTemplate = configReportTemplateMapper.selectLatestConfigReportTemplateByKey(configAssayMethodDO.getConfigReportTemplateKey());
		//指派的分析方法的参数
		List<ConfigAssayMethodParameterDO> configAssayMethodParameterDOList = configAssayMethodParameterMapper.selectByConfigAssayMethodId(assignConfigAssayMethodId);
		//分析方法检测项目配置
		List<ConfigAssayMethodProjectExtendRespVO> configAssayMethodProjectList = configAssayMethodProjectMapper.selectByConfigAssayMethodId(assignConfigAssayMethodId);
		//分析方法检测项目参数配置
		List<ConfigAssayMethodProjectParameterDO> configAssayMethodProjectParameterList = configAssayMethodProjectParameterMapper.selectByConfigAssayMethodId(assignConfigAssayMethodId);
		//分析类型
		String assayType = sampleTaskAssignContext.getAssayType();
		//分析任务数
		Integer assayTaskCount = sampleTaskAssignContext.getAssayTaskCount();
		List<AssignAssayUser> assignAssayUserList = sampleTaskAssignContext.getAssignAssayUserList();
		int assignAssayUserCount = assignAssayUserList.size();

		// 用于缓存已处理的任务单，避免同一用户在同一业务类型下重复查询数据库
	    // Key: userId + dictionaryBusinessId, Value: BusinessAssayTaskDO
	    Map<String, BusinessAssayTaskDO> existingTaskCache = new HashMap<>();

		//保存任务分配单
		List<BusinessAssayTaskDO> saveBusinessAssayTaskList = new ArrayList<>();
		//更新任务分配单
		List<BusinessAssayTaskDO> updateBusinessAssayTaskList = new ArrayList<>();
		//任务分配单明细
		List<BusinessAssayTaskDetailDO> businessAssayTaskDetailList = new ArrayList<>();
	    
		//分析的检测项目id列表
		List<Long> assayProjectDataIdList = sampleTaskAssignContext.getAssayProjectDataIdList();
		
		//查询旧的检测项目id列表
		List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataExtendList = businessAssayProjectDataMapper.selectExtendByIds(assayProjectDataIdList);
		//检测项目显示名称
//		List<String> projectShowNameList = businessAssayProjectDataExtendList.stream().map(m -> m.getShowName()).distinct().collect(Collectors.toList());
		//检测项目id列表
		List<Long> projectIdList = businessAssayProjectDataExtendList.stream().map(m -> m.getDictionaryProjectId()).distinct().collect(Collectors.toList());
		//子样id列表
		List<Long> businessSubSampleIdList = businessAssayProjectDataExtendList.stream().map(m -> m.getBusinessSubSampleId()).collect(Collectors.toList());
		//查询子样
		List<BusinessSubSampleDO> businessSubSampleList = businessSubSampleMapper.selectByIds(businessSubSampleIdList);
		sampleTaskAssignContext.setBusinessSubSampleList(businessSubSampleList);
		
		//需要更新的报表数据
		List<BusinessAssayReportDataDO> updateBusinessAssayReportDataDOList = new ArrayList<>();
		
		//需要更新的分析任务
		List<BusinessAssayTaskDataDO> updateBusinessAssayTaskDataDOList = new ArrayList<>();
		//需要更新的分析任务参数
		List<BusinessAssayTaskParameterDataDO> updateBusinessAssayTaskParameterDataDOList = new ArrayList<>();		
		//需要更新的分析任务检测项目
		List<BusinessAssayProjectDataDO> updateBusinessAssayProjectDataDOList = new ArrayList<>();
		//需要更新的分析任务检测项目参数
		List<BusinessAssayParameterDataDO> updateBusinessAssayParameterDataDOList = new ArrayList<>();
		
		//需要更新的子样判定
		List<BusinessSubSampleAssessmentDO> updateBusinessSubSampleAssessmentDOList = new ArrayList<>();
		
		//需要更新的分样判定
		List<BusinessSubParentSampleAssessmentDO> updateBusinessSubParentSampleAssessmentDOList = new ArrayList<>();
		
		//需要新建的分析任务
		List<BusinessAssayTaskDataDO> saveBusinessAssayTaskDataDOList = new ArrayList<>();
		//需要新建的分析任务参数
		List<BusinessAssayTaskParameterDataDO> saveBusinessAssayTaskParameterDataDOList = new ArrayList<>();	
		//需要新建的分析任务检测项目
		List<BusinessAssayProjectDataDO> saveBusinessAssayProjectDataDOList = new ArrayList<>();
		//需要新建的分析任务检测项目参数
		List<BusinessAssayParameterDataDO> saveBusinessAssayParameterDataDOList = new ArrayList<>();
		
		//需要新建的子样判定
		List<BusinessSubSampleAssessmentDO> saveBusinessSubSampleAssessmentDOList = new ArrayList<>();
		
		//需要新建的分样判定
		List<BusinessSubParentSampleAssessmentDO> saveBusinessSubParentSampleAssessmentDOList = new ArrayList<>();

		//需要删除的分析任务
		List<Long> removeAssayTaskDataIdList = new ArrayList<>(); 
		//需要删除的分析任务参数
		List<Long> removeAssayTaskParameterDataIdList = new ArrayList<>(); 
		//需要删除的分析任务检测项目
		List<Long> removeAssayProjectIdList = new ArrayList<>(); 
		//需要删除的分析任务检测项目参数
		List<Long> removeAssayParameterIdList = new ArrayList<>();

		//需要删除的子样判定
		List<Long> removeSubSampleAssessmentIdList = new ArrayList<>();

		//需要删除的分样判定
		List<Long> removeSubParentSampleAssessmentIdList = new ArrayList<>();
		
		//旧的根据分析方法进行分组
		Map<Long, List<BusinessAssayProjectDataExtendRespVO>> businessAssayProjectDataExtendMethodMap = businessAssayProjectDataExtendList.stream().collect(Collectors.groupingBy(BusinessAssayProjectDataExtendRespVO::getConfigAssayMethodId));

		for (Map.Entry<Long, List<BusinessAssayProjectDataExtendRespVO>> businessAssayProjectDataExtendMethodEntry : businessAssayProjectDataExtendMethodMap.entrySet()) {
			Long oldConfigAssayMethodId = businessAssayProjectDataExtendMethodEntry.getKey();
			List<BusinessAssayProjectDataExtendRespVO> currBusinessAssayProjectDataExtendList = businessAssayProjectDataExtendMethodEntry.getValue();
			//过滤当前分样id列表
			List<Long> currBusinessSubParentSampleIdList = currBusinessAssayProjectDataExtendList.stream().map(m -> m.getBusinessSubParentSampleId()).distinct().collect(Collectors.toList());
			//查询检测任务 (通过分样id，可以查询双杯样的)
			List<BusinessAssayTaskDataDO> businessAssayTaskDataDOList = businessAssayTaskDataMapper.selectByBusinessSubParentSampleIdsAndConfigAssayMethodId(currBusinessSubParentSampleIdList, oldConfigAssayMethodId);

			boolean disabled = businessAssayTaskDataDOList.stream().anyMatch(m -> m.getIsAssignTasked().equals(QmsCommonConstant.YES));
			if (disabled) {
				throw new ServiceException(1_032_001_000, "当前有样品存在已分配任务，不允许修改分析方法");
			}
		

			List<Long> businessAssayTaskDataIdList = businessAssayTaskDataDOList.stream().map(m -> m.getId()).collect(Collectors.toList());
			//查询检测任务的参数
			List<BusinessAssayTaskParameterDataExtendRespVO> businessAssayTaskParameterDataList = businessAssayTaskParameterDataMapper.selectExtendByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
			
			//查询检测任务的检测项目
			List<BusinessAssayProjectDataExtendRespVO> businessAssayProjectDataList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
			List<Long> businessAssayProjectDataIdList = businessAssayProjectDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
			//查询检测任务的检测项目的参数
			List<BusinessAssayParameterDataDO> businessAssayParameterDataDOList = businessAssayParameterDataMapper.selectByBusinessAssayProjectDataIds(businessAssayProjectDataIdList);
			
			//查询子样判定 (通过分样id，可以查询双杯样的)
			List<BusinessSubSampleAssessmentDO> businessSubSampleAssessmentDOList = businessSubSampleAssessmentMapper.selectByBusinessSubParentSampleIdsAndConfigAssayMethodId(currBusinessSubParentSampleIdList, oldConfigAssayMethodId);
			
			//查询分样判定
			List<BusinessSubParentSampleAssessmentExtendRespVO> businessSubParentSampleAssessmentList = businessSubParentSampleAssessmentMapper.selectByBusinessSubParentSampleIdsAndConfigAssayMethodId(currBusinessSubParentSampleIdList, oldConfigAssayMethodId);

			//循环分样判定
			for (BusinessSubParentSampleAssessmentExtendRespVO businessSubParentSampleAssessment : businessSubParentSampleAssessmentList) {
				//如果当前分析方法不等于要指派的方法
				if (!businessSubParentSampleAssessment.getConfigAssayMethodId().equals(assignConfigAssayMethodId)) {
					//查询是否已有要变更的方法的分样判定
					BusinessSubParentSampleAssessmentDO businessSubParentSampleAssessmentDO = businessSubParentSampleAssessmentMapper.selectByBusinessSubParentSampleIdAndConfigAssayMethodIdAndRetestCount(businessSubParentSampleAssessment.getBusinessSubParentSampleId(), assignConfigAssayMethodId, businessSubParentSampleAssessment.getRetestCount());
					if (businessSubParentSampleAssessmentDO == null) {//不存在
						//根据变更方法过滤出检测项目
//						List<Long> projectIdList = changeConfigAssayMethodProjectList.stream().filter(f -> f.getConfigAssayMethodId().equals(changeConfigAssayMethodId)).map(m -> m.getDictionaryProjectId()).distinct().collect(Collectors.toList());
						//分析类型
//						String changeAssayType = changeConfigAssayMethodProjectList.stream().filter(f -> f.getConfigAssayMethodId().equals(changeConfigAssayMethodId)).map(m -> m.getAssayType()).distinct().findFirst().orElse(null);
						
						
						//查询分析方法
//						ConfigAssayMethodDO configAssayMethodDO = configAssayMethodDOList.stream().filter(f -> f.getId().equals(changeConfigAssayMethodId)).findFirst().orElse(null);
						//查询子样分析方法
//						ConfigSubSampleMethodExtendRespVO configSubSampleMethod = configSubSampleMethodList.stream().filter(f -> f.getConfigSubSampleParentId().equals(businessSubParentSampleAssessment.getConfigSubSampleParentId()) && f.getConfigAssayMethodId().equals(changeConfigAssayMethodId)).findFirst().orElse(null);
//						switch (changeAssayType) {//根据前端传入的分析类型，修改子样分析方法中的分析任务数
//						case QmsCommonConstant.ASSAY_TYPE_SINGLE_PARALLEL: {
//							configSubSampleMethod.setTaskCount(2);//平行
//							break;
//						}
//						default:
//							configSubSampleMethod.setTaskCount(1);//单杯
//							break;
//						}
//						
//						//扩展配置
//				    	String configInfomation = configSubSampleMethod.getConfigInfomation();
//						List<ConfigSubSampleMethodConfItem> getParamList = null;
//				    	if (StringUtils.isNotBlank(configInfomation)) {
//				    		//解析配置
//							ConfigSubSampleMethodConfInfo configSubSampleMethodConfInfo = JSON.parseObject(configInfomation, ConfigSubSampleMethodConfInfo.class);
//							getParamList = configSubSampleMethodConfInfo.getGetParam();
//						}
//						
//						//根据任务数判断是平行还是
//						String assayType = configSubSampleMethod.getTaskCount() > 1 ? QmsCommonConstant.ASSAY_TYPE_SINGLE_PARALLEL : QmsCommonConstant.ASSAY_TYPE_SINGLE_CUP;
						
						businessSubParentSampleAssessmentDO = new BusinessSubParentSampleAssessmentDO();
						businessSubParentSampleAssessmentDO.setId(IdWorker.getId());
						businessSubParentSampleAssessmentDO.setBusinessSubParentSampleId(businessSubParentSampleAssessment.getBusinessSubParentSampleId());
						businessSubParentSampleAssessmentDO.setConfigAssayMethodId(assignConfigAssayMethodId);
						businessSubParentSampleAssessmentDO.setAssayType(assayType);
						businessSubParentSampleAssessmentDO.setTaskType("常规");
						saveBusinessSubParentSampleAssessmentDOList.add(businessSubParentSampleAssessmentDO);
						
						BusinessSubSampleDO businessSubSampleDO = null;
						if (!QmsCommonConstant.ASSAY_TYPE_DOUBLE_CUP.equals(businessSubParentSampleAssessment.getAssayType())) {//如果不为双杯样
							businessSubSampleDO = businessSubSampleList.stream().filter(f -> f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).findFirst().orElse(null);
						}

						//子样判定数据
						BusinessSubSampleAssessmentDO businessSubSampleAssessmentDO = new BusinessSubSampleAssessmentDO();
						businessSubSampleAssessmentDO.setId(IdWorker.getId());	
						businessSubSampleAssessmentDO.setBusinessBaseSampleId(businessSubParentSampleAssessment.getBusinessBaseSampleId());
						businessSubSampleAssessmentDO.setBusinessSubParentSampleId(businessSubParentSampleAssessment.getBusinessSubParentSampleId());
						businessSubSampleAssessmentDO.setBusinessSubParentSampleAssessmentId(businessSubParentSampleAssessmentDO.getId());
						if (businessSubSampleDO != null) {
							businessSubSampleAssessmentDO.setBusinessSubSampleId(businessSubSampleDO.getId());
						}
						businessSubSampleAssessmentDO.setConfigAssayMethodId(assignConfigAssayMethodId);
						businessSubSampleAssessmentDO.setAssayType(assayType);
						businessSubSampleAssessmentDO.setTaskType("常规");
						
						saveBusinessSubSampleAssessmentDOList.add(businessSubSampleAssessmentDO);
						
						//查询需要删除的检测项目
						List<Long> removBusinessAssayProjectDataIdList = currBusinessAssayProjectDataExtendList.stream().filter(f -> f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).map(m -> m.getId()).collect(Collectors.toList());
						//添加到删除列表
						removeAssayProjectIdList.addAll(removBusinessAssayProjectDataIdList);
						List<Long> removBusinessAssayParameterDataIdList = businessAssayParameterDataDOList.stream().filter(f -> removBusinessAssayProjectDataIdList.contains(f.getBusinessAssayProjectDataId())).map(m -> m.getId()).collect(Collectors.toList());
						removeAssayParameterIdList.addAll(removBusinessAssayParameterDataIdList);
						
//						List<Long> oldBusinessAssayProjectDataIdList = businessAssayProjectDataList.stream().filter(f -> f.getConfigAssayMethodId().equals(businessSubParentSampleAssessment.getConfigAssayMethodId()) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).map(m -> m.getId()).collect(Collectors.toList());

						List<String> projectShowNameList = businessAssayProjectDataList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId()) && !removeAssayProjectIdList.contains(f.getId())).map(m -> m.getShowName()).collect(Collectors.toList());
						
						if (projectShowNameList.size() <= 0) {
							//查询旧的检测任务
							List<Long> oldBusinessAssayTaskDataIdList = businessAssayTaskDataDOList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).map(m -> m.getId()).collect(Collectors.toList());
							//添加到删除列表
							removeAssayTaskDataIdList.addAll(oldBusinessAssayTaskDataIdList);
							if (oldBusinessAssayTaskDataIdList.size() > 0) {
								List<Long> oldBusinessAssayTaskParameterDataIdList = businessAssayTaskParameterDataList.stream().filter(f -> oldBusinessAssayTaskDataIdList.contains(f.getBusinessAssayTaskDataId())).map(m -> m.getId()).collect(Collectors.toList());
								//添加分析任务属性删除列表
								removeAssayTaskParameterDataIdList.addAll(oldBusinessAssayTaskParameterDataIdList);
							}
							//查询旧的子样判定
							List<Long> oldBusinessSubSampleAssesmentIdList = businessSubSampleAssessmentDOList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).map(m -> m.getId()).collect(Collectors.toList());
							//添加到删除列表
							removeSubSampleAssessmentIdList.addAll(oldBusinessSubSampleAssesmentIdList);
							
							//添加到删除列表
							removeSubParentSampleAssessmentIdList.add(businessSubParentSampleAssessment.getId());
						} else {
							//查询旧的检测任务
							List<BusinessAssayTaskDataDO> oldBusinessAssayTaskDataList = businessAssayTaskDataDOList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).collect(Collectors.toList());
							for (BusinessAssayTaskDataDO oldBusinessAssayTaskData : oldBusinessAssayTaskDataList) {
								boolean isAdd = updateBusinessAssayTaskDataDOList.stream().anyMatch(m -> m.getId().equals(oldBusinessAssayTaskData.getId()));
								if (!isAdd) {//如果未添加过更新，则修改检测项目并添加更新
									oldBusinessAssayTaskData.setAssayProject(CollUtil.join(projectShowNameList, ","));
									updateBusinessAssayTaskDataDOList.add(oldBusinessAssayTaskData);
								}
							}
						}
						
						BusinessAssayTaskDataDO oldBusinessAssayTaskDataDO = businessAssayTaskDataDOList.stream().filter(f -> f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).findFirst().orElse(null);
						
						//根据检测方法循环
						BusinessAssayTaskDataDO businessAssayTaskDataDO = null;
						//根据任务数循环
						for (int i = 0; i < assayTaskCount; i++) {
							//子样检测任务
							businessAssayTaskDataDO = new BusinessAssayTaskDataDO();
							businessAssayTaskDataDO.setId(IdWorker.getId());
							businessAssayTaskDataDO.setBusinessBaseSampleId(businessSubSampleDO.getBusinessBaseSampleId());
							businessAssayTaskDataDO.setBusinessSubParentSampleId(businessSubSampleDO.getBusinessSubParentSampleId());
							businessAssayTaskDataDO.setBusinessSubSampleId(businessSubSampleDO.getId());
							businessAssayTaskDataDO.setBusinessSubSampleAssessmentId(businessSubSampleAssessmentDO.getId());//子样判定id
							businessAssayTaskDataDO.setConfigAssayMethodId(assignConfigAssayMethodId);
							businessAssayTaskDataDO.setAssayType(assayType);
							businessAssayTaskDataDO.setTaskType("常规");
							businessAssayTaskDataDO.setConfigSampleFlowId(oldBusinessAssayTaskDataDO.getConfigSampleFlowId());
							businessAssayTaskDataDO.setSampleFlowNodeKey(oldBusinessAssayTaskDataDO.getSampleFlowNodeKey());
							businessAssayTaskDataDO.setSampleFlowNodeTime(currentDateTime);
							businessAssayTaskDataDO.setAssayDepartmentId(configAssayMethodDO.getAssayDepartmentId());
							businessAssayTaskDataDO.setAssayDepartmentName(configAssayMethodDO.getAssayDepartmentName());
							
				            // 1. 确定当前数据分配给哪个用户 (轮询)
				            AssignAssayUser currentUser = assignAssayUserList.get(i % assignAssayUserCount);
				            String currentOperatorName = currentUser.getRealName();
				            Long currentOperatorId = currentUser.getUserId();

				            // 2. 查找或创建该用户在此业务类型下的任务单
				            // 缓存Key：用户ID_业务ID
				            String cacheKey = currentOperatorId + "_" + dictionaryBusinessId;
				            BusinessAssayTaskDO businessAssayTaskDO = existingTaskCache.get(cacheKey);

				            if (businessAssayTaskDO == null) {
				                // 缓存没命中，去数据库查该用户是否有进行中的任务
				                businessAssayTaskDO = businessAssayTaskMapper.selectAssignInProgressByAssayUserAndAssignUser(dictionaryBusinessId, currentOperatorName, loginRealname);
				                
				                if (businessAssayTaskDO == null) {
				                    // 没有进行中任务，新建
				                    String taskNo = sequenceUtil.genCode(configAssayMethodDO.getCodeRule());
				                    businessAssayTaskDO = new BusinessAssayTaskDO();
				                    businessAssayTaskDO.setId(IdWorker.getId());
				                    businessAssayTaskDO.setTaskNo(taskNo);
				                    businessAssayTaskDO.setTaskName(dictionaryBusinessDO.getName());
				                    
				                    // 设置当前轮询到的操作员
				                    businessAssayTaskDO.setAssayOperator(currentOperatorName);
				                    businessAssayTaskDO.setAssayOperatorId(currentOperatorId);
				                    
				                    businessAssayTaskDO.setConfigAssayMethodId(configAssayMethodDO.getId());
				                    businessAssayTaskDO.setDictionaryBusinessId(dictionaryBusinessId);
				                    businessAssayTaskDO.setDictionaryBusinessKey(configAssayMethodDO.getDictionaryBusinessKey());
				                    businessAssayTaskDO.setTaskSourceType(QmsCommonConstant.TASK_ASSIGN);
				                    businessAssayTaskDO.setConfigReportTemplateId(configReportTemplate.getId());
				                    businessAssayTaskDO.setConfigReportTemplateKey(configReportTemplate.getKey());
				                    businessAssayTaskDO.setIsIngredients(configAssayMethodDO.getIsIngredients());
				                    businessAssayTaskDO.setIngredientsStatus("initial");

				                    businessAssayTaskDO.setTaskAssignOperator(loginRealname);
				                    businessAssayTaskDO.setTaskAssignOperatorId(loginUser.getId());
				                    businessAssayTaskDO.setTaskAssignTime(currentDateTime);
				                    businessAssayTaskDO.setTaskAssignStatus(QmsCommonConstant.IN_PROGRESS);
				                    businessAssayTaskDO.setTaskAssayStatus(QmsCommonConstant.NOT_START);
				                    businessAssayTaskDO.setFinishStatus(QmsCommonConstant.NOT_START);
				                    businessAssayTaskDO.setFlowStatus(QmsCommonConstant.NOT_START);

				                    saveBusinessAssayTaskList.add(businessAssayTaskDO);
				                } else {
				                    updateBusinessAssayTaskList.add(businessAssayTaskDO);
				                }
				                // 放入缓存，后续同用户同业务类型的直接复用
				                existingTaskCache.put(cacheKey, businessAssayTaskDO);
				            }

				            // 3. 更新原始数据状态
				            businessAssayTaskDataDO.setIsAssignTasked(QmsCommonConstant.YES);
				            businessAssayTaskDataDO.setAssignTaskTime(currentDateTime);
				            // 注意：这里也要更新为当前轮询到的操作员，而不是固定的某个人
				            businessAssayTaskDataDO.setAssayOperator(currentOperatorName);
				            businessAssayTaskDataDO.setAssayOperatorId(currentOperatorId);
				            businessAssayTaskDataDO.setBusinessAssayTaskId(businessAssayTaskDO.getId());

				            // 4. 构建任务明细
				            BusinessAssayTaskDetailDO businessAssayTaskDetailDO = new BusinessAssayTaskDetailDO();
				            businessAssayTaskDetailDO.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
				            businessAssayTaskDetailDO.setBusinessAssayTaskId(businessAssayTaskDO.getId());
				            businessAssayTaskDetailDO.setTaskNo(businessAssayTaskDO.getTaskNo());
				            businessAssayTaskDetailDO.setSampleId(businessAssayTaskDataDO.getBusinessSubSampleId());
				            businessAssayTaskDetailDO.setSampleCode(businessSubSampleDO.getSampleAssayCode());
				            businessAssayTaskDetailDO.setSampleName(businessSubSampleDO.getSampleName());
				            businessAssayTaskDetailDO.setDataSourceType(QmsCommonConstant.NORMAL);
				            // 如果需要全局排序，这里的 sortNo 可能需要重新计算，如果是按任务单内部排序，保持自增即可
				            // 由于现在拆分了任务单，每个任务单内部的 sortNo 最好单独维护，这里简单处理为累加（实际可能需按任务单分组后重排）
				            // 建议：如果在同一个任务单内，sortNo 应该是连续的。由于我们是循环插入，可能需要后期整理，或者在这里维护一个 Map<TaskId, SortNo>
				            // 为了简化，这里暂时保持原有逻辑，实际生产中建议在循环结束后按 taskId 分组重新设置 sortNo
				            
				            businessAssayTaskDetailList.add(businessAssayTaskDetailDO);
				            
							
							//子样检测任务参数
							BusinessAssayTaskParameterDataDO businessAssayTaskParameterDataDO = null;
							for (ConfigAssayMethodParameterDO configAssayMethodParameterDO : configAssayMethodParameterDOList) {
								businessAssayTaskParameterDataDO = new BusinessAssayTaskParameterDataDO();
								businessAssayTaskParameterDataDO.setId(IdWorker.getId());
								businessAssayTaskParameterDataDO.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
								businessAssayTaskParameterDataDO.setConfigAssayMethodParameterId(configAssayMethodParameterDO.getId());
								businessAssayTaskParameterDataDO.setDataType(configAssayMethodParameterDO.getDataType());
								businessAssayTaskParameterDataDO.setDecimalPosition(configAssayMethodParameterDO.getDecimalPosition());	
								
								if (StringUtils.isNotBlank(configAssayMethodParameterDO.getDefaultValue())) {
									businessAssayTaskParameterDataDO.setValue(configAssayMethodParameterDO.getDefaultValue());
								}
//								if (getParamList != null) {
//									BusinessAssayTaskParameterDataExtendRespVO oldBusinessAssayTaskParameterData = businessAssayTaskParameterDataList.stream().filter(f -> f.getConfigAssayMethodId().equals(configAssayMethodId) && f.getBusinessAssayTaskDataId().equals(oldBusinessAssayTaskDataDO.getId()) && f.getKey().equals(configAssayMethodParameterDO.getKey())).findFirst().orElse(null);
//									ConfigSubSampleMethodConfItem targetAttribute = getParamList.stream().filter(f -> StringUtils.isNotBlank(f.getTarget().getAttribute()) && f.getTarget().getAttribute().equals(oldBusinessAssayTaskParameterData.getKey())).findFirst().orElse(null);
//									if (targetAttribute != null) {
//										businessAssayTaskParameterDataDO.setValue(oldBusinessAssayTaskParameterData.getValue());
//									}
//								}

								saveBusinessAssayTaskParameterDataDOList.add(businessAssayTaskParameterDataDO);
							}
														
							StringBuilder assayProjectBuilder = new StringBuilder();
							
							for (ConfigAssayMethodProjectExtendRespVO configAssayMethodProjectDO : configAssayMethodProjectList) {
								
								//如果当前分析方法的项目不在当前检测项目中，则跳出循环继续
								if (!projectIdList.contains(configAssayMethodProjectDO.getDictionaryProjectId())) {
									continue;
								}
								
								assayProjectBuilder.append(configAssayMethodProjectDO.getShowName()).append(",");
								

								//检测项目
								BusinessAssayProjectDataDO businessAssayProjectDataDO = new BusinessAssayProjectDataDO();
								businessAssayProjectDataDO.setId(IdWorker.getId());
								businessAssayProjectDataDO.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
								businessAssayProjectDataDO.setConfigAssayMethodProjectId(configAssayMethodProjectDO.getId());
								businessAssayProjectDataDO.setDictionaryProjectId(configAssayMethodProjectDO.getDictionaryProjectId());
								businessAssayProjectDataDO.setDataType(configAssayMethodProjectDO.getDataType());
								businessAssayProjectDataDO.setDecimalPosition(configAssayMethodProjectDO.getDecimalPosition());
								businessAssayProjectDataDO.setEffectiveDigit(configAssayMethodProjectDO.getEffectiveDigit());
								businessAssayProjectDataDO.setUsage(QmsCommonConstant.ASSAY_PROJECT_USAGE_REPORT);
								businessAssayProjectDataDO.setMinimumLimitValue(configAssayMethodProjectDO.getMinimumLimitValue());
								businessAssayProjectDataDO.setIsEnabled(QmsCommonConstant.YES);
								businessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.NO);
								
								saveBusinessAssayProjectDataDOList.add(businessAssayProjectDataDO);
								
								List<ConfigAssayMethodProjectParameterDO> configAssayMethodProjectParameterDOList = configAssayMethodProjectParameterList.stream().filter(f -> f.getConfigAssayMethodProjectId().equals(configAssayMethodProjectDO.getId())).collect(Collectors.toList());
								for (ConfigAssayMethodProjectParameterDO configAssayMethodProjectParameterDO : configAssayMethodProjectParameterDOList) {
									BusinessAssayParameterDataDO businessAssayParameterDataDO = new BusinessAssayParameterDataDO();
									businessAssayParameterDataDO.setId(IdWorker.getId());
									businessAssayParameterDataDO.setConfigAssayMethodProjectParameterId(configAssayMethodProjectParameterDO.getId());
									businessAssayParameterDataDO.setBusinessAssayProjectDataId(businessAssayProjectDataDO.getId());
									businessAssayParameterDataDO.setDictionaryParameterId(configAssayMethodProjectParameterDO.getDictionaryParameterId());
									businessAssayParameterDataDO.setDataType(configAssayMethodProjectParameterDO.getDataType());
									businessAssayParameterDataDO.setDecimalPosition(configAssayMethodProjectParameterDO.getDecimalPosition());
									
									if (StringUtils.isNotBlank(configAssayMethodProjectParameterDO.getDefaultValue())) {
										businessAssayParameterDataDO.setValue(configAssayMethodProjectParameterDO.getDefaultValue());
									}
									
									saveBusinessAssayParameterDataDOList.add(businessAssayParameterDataDO);
								}
							}
							if (assayProjectBuilder.length() > 1) {
								assayProjectBuilder.delete(assayProjectBuilder.length() - 1 , assayProjectBuilder.length());
							}
							businessAssayTaskDataDO.setAssayProject(assayProjectBuilder.toString());
							saveBusinessAssayTaskDataDOList.add(businessAssayTaskDataDO);
						}
						
					} else {//已存在
						//分析类型
//						String changeAssayType = changeConfigAssayMethodProjectList.stream().filter(f -> f.getConfigAssayMethodId().equals(changeConfigAssayMethodId)).map(m -> m.getAssayType()).distinct().findFirst().orElse(null);
//						if (!businessSubParentSampleAssessmentDO.getAssayType().equals(changeAssayType)) {
//							String configAssayMethodNameAndCategory = changeConfigAssayMethodProjectList.stream().filter(f -> f.getConfigAssayMethodId().equals(changeConfigAssayMethodId)).map(m -> m.getConfigAssayMethodNameAndCategory()).distinct().findFirst().orElse(null);
//							throw new ServiceException(1_032_001_000, "检测方法“"+configAssayMethodNameAndCategory+"”，存在与当前分析类型不同的分析任务！");
//						}
						
						//根据变更方法过滤出检测项目
//						List<Long> projectIdList = changeConfigAssayMethodProjectList.stream().filter(f -> f.getConfigAssayMethodId().equals(changeConfigAssayMethodId)).map(m -> m.getDictionaryProjectId()).distinct().collect(Collectors.toList());
						
						//查询分析方法
						//ConfigAssayMethodDO configAssayMethodDO = configAssayMethodDOList.stream().filter(f -> f.getId().equals(changeConfigAssayMethodId)).findFirst().orElse(null);
						//查询子样分析方法
						//ConfigSubSampleMethodExtendRespVO configSubSampleMethod = configSubSampleMethodList.stream().filter(f -> f.getConfigSubSampleParentId().equals(businessSubParentSampleAssessment.getConfigSubSampleParentId()) && f.getConfigAssayMethodId().equals(changeConfigAssayMethodId)).findFirst().orElse(null);

						//根据任务数判断是平行还是
						//String assayType = configSubSampleMethod.getTaskCount() > 1 ? QmsCommonConstant.ASSAY_TYPE_SINGLE_PARALLEL : QmsCommonConstant.ASSAY_TYPE_SINGLE_CUP;
						
						//查询子样判定
						//BusinessSubSampleAssessmentDO businessSubSampleAssessmentDO = businessSubSampleAssessmentMapper.selectByBusinessSubParentSampleIdAndConfigAssayMethodId(businessSubParentSampleAssessmentDO.getBusinessSubParentSampleId(), changeConfigAssayMethodId);

						//查询旧的检测项目
						List<Long> oldBusinessAssayProjectDataIdList = businessAssayProjectDataList.stream().filter(f -> projectIdList.contains(f.getDictionaryProjectId()) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).map(m -> m.getId()).collect(Collectors.toList());
						//添加到删除列表
						removeAssayProjectIdList.addAll(oldBusinessAssayProjectDataIdList);
						List<Long> oldBusinessAssayParameterDataIdList = businessAssayParameterDataDOList.stream().filter(f -> oldBusinessAssayProjectDataIdList.contains(f.getBusinessAssayProjectDataId())).map(m -> m.getId()).collect(Collectors.toList());
						removeAssayParameterIdList.addAll(oldBusinessAssayParameterDataIdList);

//						List<String> projectShowNameList = changeConfigAssayMethodProjectList.stream().filter(f -> f.getConfigAssayMethodId().equals(configAssayMethodId)).map(m -> m.getDictionaryProjectShowName()).distinct().collect(Collectors.toList());
						List<String> projectShowNameList = businessAssayProjectDataList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId()) && !removeAssayProjectIdList.contains(f.getId())).map(m -> m.getShowName()).collect(Collectors.toList());
						
						if (projectShowNameList.size() <= 0) {//当前方法无检测项目，则需要删除
							//查询旧的检测任务
							List<Long> oldBusinessAssayTaskDataIdList = businessAssayTaskDataDOList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).map(m -> m.getId()).collect(Collectors.toList());
							//添加到删除列表
							removeAssayTaskDataIdList.addAll(oldBusinessAssayTaskDataIdList);
							//查询旧的子样判定
							List<Long> oldBusinessSubSampleAssesmentIdList = businessSubSampleAssessmentDOList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).map(m -> m.getId()).collect(Collectors.toList());
							//添加到删除列表
							removeSubSampleAssessmentIdList.addAll(oldBusinessSubSampleAssesmentIdList);
							
							//添加到删除列表
							removeSubParentSampleAssessmentIdList.add(businessSubParentSampleAssessment.getId());
						} else {
							//查询旧的检测任务
							List<BusinessAssayTaskDataDO> oldBusinessAssayTaskDataList = businessAssayTaskDataDOList.stream().filter(f -> f.getConfigAssayMethodId().equals(oldConfigAssayMethodId) && f.getBusinessSubParentSampleId().equals(businessSubParentSampleAssessment.getBusinessSubParentSampleId())).collect(Collectors.toList());
							for (BusinessAssayTaskDataDO oldBusinessAssayTaskData : oldBusinessAssayTaskDataList) {
								boolean isAdd = updateBusinessAssayTaskDataDOList.stream().anyMatch(m -> m.getId().equals(oldBusinessAssayTaskData.getId()));
								if (!isAdd) {//如果未添加过更新，则修改检测项目并添加更新
									oldBusinessAssayTaskData.setAssayProject(CollUtil.join(projectShowNameList, ","));
									updateBusinessAssayTaskDataDOList.add(oldBusinessAssayTaskData);
								}
							}
						}

						//查询当前存在的分析任务
						List<BusinessAssayTaskDataDO> currBusinessAssayTaskDataDOList = businessAssayTaskDataMapper.selectByBusinessSubParentSampleIdAndConfigAssayMethodId(businessSubParentSampleAssessmentDO.getBusinessSubParentSampleId(), assignConfigAssayMethodId);
						
						int i = 0;
						//当前存在的分析任务循环
						for (BusinessAssayTaskDataDO businessAssayTaskDataDO : currBusinessAssayTaskDataDOList) {
							
							List<ConfigAssayMethodProjectExtendRespVO> configAssayMethodProjectDOList = configAssayMethodProjectList.stream().filter(f -> f.getConfigAssayMethodId().equals(assignConfigAssayMethodId)).collect(Collectors.toList());
							
							StringBuilder assayProjectBuilder = new StringBuilder(businessAssayTaskDataDO.getAssayProject());
							assayProjectBuilder.append(",");
							
							for (ConfigAssayMethodProjectExtendRespVO configAssayMethodProjectDO : configAssayMethodProjectDOList) {
								
								//如果当前分析方法的项目不在当前检测项目中，则跳出循环继续
								if (!projectIdList.contains(configAssayMethodProjectDO.getDictionaryProjectId())) {
									continue;
								}
								
								assayProjectBuilder.append(configAssayMethodProjectDO.getShowName()).append(",");
								

								//检测项目
								BusinessAssayProjectDataDO businessAssayProjectDataDO = new BusinessAssayProjectDataDO();
								businessAssayProjectDataDO.setId(IdWorker.getId());
								businessAssayProjectDataDO.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
								businessAssayProjectDataDO.setConfigAssayMethodProjectId(configAssayMethodProjectDO.getId());
								businessAssayProjectDataDO.setDictionaryProjectId(configAssayMethodProjectDO.getDictionaryProjectId());
								businessAssayProjectDataDO.setDataType(configAssayMethodProjectDO.getDataType());
								businessAssayProjectDataDO.setDecimalPosition(configAssayMethodProjectDO.getDecimalPosition());
								businessAssayProjectDataDO.setEffectiveDigit(configAssayMethodProjectDO.getEffectiveDigit());
								businessAssayProjectDataDO.setUsage(QmsCommonConstant.ASSAY_PROJECT_USAGE_REPORT);
								businessAssayProjectDataDO.setMinimumLimitValue(configAssayMethodProjectDO.getMinimumLimitValue());
								businessAssayProjectDataDO.setIsEnabled(QmsCommonConstant.YES);
								businessAssayProjectDataDO.setIsNotAssessment(QmsCommonConstant.NO);
								
								saveBusinessAssayProjectDataDOList.add(businessAssayProjectDataDO);
								
								List<ConfigAssayMethodProjectParameterDO> configAssayMethodProjectParameterDOList = configAssayMethodProjectParameterList.stream().filter(f -> f.getConfigAssayMethodProjectId().equals(configAssayMethodProjectDO.getId())).collect(Collectors.toList());
								for (ConfigAssayMethodProjectParameterDO configAssayMethodProjectParameterDO : configAssayMethodProjectParameterDOList) {
									BusinessAssayParameterDataDO businessAssayParameterDataDO = new BusinessAssayParameterDataDO();
									businessAssayParameterDataDO.setId(IdWorker.getId());
									businessAssayParameterDataDO.setConfigAssayMethodProjectParameterId(configAssayMethodProjectParameterDO.getId());
									businessAssayParameterDataDO.setBusinessAssayProjectDataId(businessAssayProjectDataDO.getId());
									businessAssayParameterDataDO.setDictionaryParameterId(configAssayMethodProjectParameterDO.getDictionaryParameterId());
									businessAssayParameterDataDO.setDataType(configAssayMethodProjectParameterDO.getDataType());
									businessAssayParameterDataDO.setDecimalPosition(configAssayMethodProjectParameterDO.getDecimalPosition());
									
									saveBusinessAssayParameterDataDOList.add(businessAssayParameterDataDO);
								}
							}
							if (assayProjectBuilder.length() > 1) {
								assayProjectBuilder.delete(assayProjectBuilder.length() - 1 , assayProjectBuilder.length());
							}
							businessAssayTaskDataDO.setAssayProject(assayProjectBuilder.toString());
							

				            // 1. 确定当前数据分配给哪个用户 (轮询)
				            AssignAssayUser currentUser = assignAssayUserList.get(i % assignAssayUserCount);
				            String currentOperatorName = currentUser.getRealName();
				            Long currentOperatorId = currentUser.getUserId();

				            // 2. 查找或创建该用户在此业务类型下的任务单
				            // 缓存Key：用户ID_业务ID
				            String cacheKey = currentOperatorId + "_" + dictionaryBusinessId;
				            BusinessAssayTaskDO businessAssayTaskDO = existingTaskCache.get(cacheKey);

				            if (businessAssayTaskDO == null) {
				                // 缓存没命中，去数据库查该用户是否有进行中的任务
				                businessAssayTaskDO = businessAssayTaskMapper.selectAssignInProgressByAssayUserAndAssignUser(dictionaryBusinessId, currentOperatorName, loginRealname);
				                
				                if (businessAssayTaskDO == null) {
				                    // 没有进行中任务，新建
				                    String taskNo = sequenceUtil.genCode(configAssayMethodDO.getCodeRule());
				                    businessAssayTaskDO = new BusinessAssayTaskDO();
				                    businessAssayTaskDO.setId(IdWorker.getId());
				                    businessAssayTaskDO.setTaskNo(taskNo);
				                    businessAssayTaskDO.setTaskName(dictionaryBusinessDO.getName());
				                    
				                    // 设置当前轮询到的操作员
				                    businessAssayTaskDO.setAssayOperator(currentOperatorName);
				                    businessAssayTaskDO.setAssayOperatorId(currentOperatorId);
				                    
				                    businessAssayTaskDO.setConfigAssayMethodId(configAssayMethodDO.getId());
				                    businessAssayTaskDO.setDictionaryBusinessId(dictionaryBusinessId);
				                    businessAssayTaskDO.setDictionaryBusinessKey(configAssayMethodDO.getDictionaryBusinessKey());
				                    businessAssayTaskDO.setTaskSourceType(QmsCommonConstant.TASK_ASSIGN);
				                    businessAssayTaskDO.setConfigReportTemplateId(configReportTemplate.getId());
				                    businessAssayTaskDO.setConfigReportTemplateKey(configReportTemplate.getKey());
				                    businessAssayTaskDO.setIsIngredients(configAssayMethodDO.getIsIngredients());
				                    businessAssayTaskDO.setIngredientsStatus("initial");

				                    businessAssayTaskDO.setTaskAssignOperator(loginRealname);
				                    businessAssayTaskDO.setTaskAssignOperatorId(loginUser.getId());
				                    businessAssayTaskDO.setTaskAssignTime(currentDateTime);
				                    businessAssayTaskDO.setTaskAssignStatus(QmsCommonConstant.IN_PROGRESS);
				                    businessAssayTaskDO.setTaskAssayStatus(QmsCommonConstant.NOT_START);
				                    businessAssayTaskDO.setFinishStatus(QmsCommonConstant.NOT_START);
				                    businessAssayTaskDO.setFlowStatus(QmsCommonConstant.NOT_START);

				                    saveBusinessAssayTaskList.add(businessAssayTaskDO);
				                } else {
				                    updateBusinessAssayTaskList.add(businessAssayTaskDO);
				                }
				                // 放入缓存，后续同用户同业务类型的直接复用
				                existingTaskCache.put(cacheKey, businessAssayTaskDO);
				            }

				            // 3. 更新原始数据状态
				            businessAssayTaskDataDO.setIsAssignTasked(QmsCommonConstant.YES);
				            businessAssayTaskDataDO.setAssignTaskTime(currentDateTime);
				            // 注意：这里也要更新为当前轮询到的操作员，而不是固定的某个人
				            businessAssayTaskDataDO.setAssayOperator(currentOperatorName);
				            businessAssayTaskDataDO.setAssayOperatorId(currentOperatorId);
				            businessAssayTaskDataDO.setBusinessAssayTaskId(businessAssayTaskDO.getId());

				            // 4. 构建任务明细
				            BusinessSubSampleDO businessSubSampleDO = sampleTaskAssignContext.getBusinessSubSampleById(businessAssayTaskDataDO.getBusinessSubSampleId());
				            
				            BusinessAssayTaskDetailDO businessAssayTaskDetailDO = new BusinessAssayTaskDetailDO();
				            businessAssayTaskDetailDO.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
				            businessAssayTaskDetailDO.setBusinessAssayTaskId(businessAssayTaskDO.getId());
				            businessAssayTaskDetailDO.setTaskNo(businessAssayTaskDO.getTaskNo());
				            businessAssayTaskDetailDO.setSampleId(businessAssayTaskDataDO.getBusinessSubSampleId());
				            businessAssayTaskDetailDO.setSampleCode(businessSubSampleDO.getSampleAssayCode());
				            businessAssayTaskDetailDO.setSampleName(businessSubSampleDO.getSampleName());
				            businessAssayTaskDetailDO.setDataSourceType(QmsCommonConstant.NORMAL);
				            // 如果需要全局排序，这里的 sortNo 可能需要重新计算，如果是按任务单内部排序，保持自增即可
				            // 由于现在拆分了任务单，每个任务单内部的 sortNo 最好单独维护，这里简单处理为累加（实际可能需按任务单分组后重排）
				            // 建议：如果在同一个任务单内，sortNo 应该是连续的。由于我们是循环插入，可能需要后期整理，或者在这里维护一个 Map<TaskId, SortNo>
				            // 为了简化，这里暂时保持原有逻辑，实际生产中建议在循环结束后按 taskId 分组重新设置 sortNo
				            
				            businessAssayTaskDetailList.add(businessAssayTaskDetailDO);
							
							updateBusinessAssayTaskDataDOList.add(businessAssayTaskDataDO);
							i++;
						}
						
						
					}
					
				
					
					
					
				}
				
			}
			
			
		}

	    Map<Long, Integer> sortCounterMap = new HashMap<>();
	    for (BusinessAssayTaskDetailDO detail : businessAssayTaskDetailList) {
	        Long taskId = detail.getBusinessAssayTaskId();
	        int currentSort = sortCounterMap.getOrDefault(taskId, 0) + 1;
	        detail.setSortNo(currentSort);
	        sortCounterMap.put(taskId, currentSort);
	    }
	    

	    sampleTaskAssignContext.setSaveBusinessSubParentSampleAssessmentList(saveBusinessSubParentSampleAssessmentDOList);
	    sampleTaskAssignContext.setSaveBusinessSubSampleAssessmentList(saveBusinessSubSampleAssessmentDOList);
	    
		sampleTaskAssignContext.setSaveBusinessAssayTaskList(saveBusinessAssayTaskList);
		sampleTaskAssignContext.setUpdateBusinessAssayTaskList(updateBusinessAssayTaskList);
		
		sampleTaskAssignContext.setSaveBusinessAssayTaskDataList(saveBusinessAssayTaskDataDOList);
		sampleTaskAssignContext.setBusinessAssayTaskDataList(updateBusinessAssayTaskDataDOList);
		
		sampleTaskAssignContext.setSaveBusinessAssayTaskParameterDataList(saveBusinessAssayTaskParameterDataDOList);
		
		sampleTaskAssignContext.setSaveBusinessAssayProjectDataList(saveBusinessAssayProjectDataDOList);
		sampleTaskAssignContext.setSaveBusinessAssayParameterDataList(saveBusinessAssayParameterDataDOList);
		
		sampleTaskAssignContext.setBusinessAssayTaskDetailList(businessAssayTaskDetailList);
		
		sampleTaskAssignContext.setRemoveAssayTaskDataIdList(removeAssayTaskDataIdList);
		sampleTaskAssignContext.setRemoveAssayTaskParameterDataIdList(removeAssayTaskParameterDataIdList);
		sampleTaskAssignContext.setRemoveAssayProjectIdList(removeAssayProjectIdList);
		sampleTaskAssignContext.setRemoveAssayParameterIdList(removeAssayParameterIdList);
		sampleTaskAssignContext.setRemoveSubSampleAssessmentIdList(removeSubSampleAssessmentIdList);
		sampleTaskAssignContext.setRemoveSubParentSampleAssessmentIdList(removeSubParentSampleAssessmentIdList);
}

	@Override
	public boolean isAccess() {
		SampleTaskAssignContext sampleTaskAssignContext = this.getContextBean(SampleTaskAssignContext.class);
		return sampleTaskAssignContext.getSampleTaskAssignType().equals(SampleTaskAssignTypeEnum.PROJECT_METHOD);
	}
}
