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.Set;
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.security.core.LoginUser;
import com.zt.plat.module.qms.business.bus.controller.vo.BusinessSampleEntrustUnStandardProjectExtendRespVO;
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.BusinessSampleEntrustUnStandardProjectDO;
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.BusinessAssayTaskDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustUnStandardProjectMapper;
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.bean.BeanUtil;
import jakarta.annotation.Resource;

@LiteflowComponent(id = "sampleTaskAssignProjectNoMethodCmp", name = "手动分配(按检测项目未指定方法分配)")
public class SampleTaskAssignProjectNoMethodCmp 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 BusinessSampleEntrustUnStandardProjectMapper businessSampleEntrustUnStandardProjectMapper;
	
	@Resource
	private BusinessAssayTaskDataMapper businessAssayTaskDataMapper;
	
	@Resource
	private BusinessAssayTaskMapper businessAssayTaskMapper;
	
	@Resource
	private BusinessSubSampleMapper businessSubSampleMapper;
	
	@Resource
	private BusinessSubParentSampleAssessmentMapper businessSubParentSampleAssessmentMapper;
	
	@Resource
	private BusinessSubSampleAssessmentMapper businessSubSampleAssessmentMapper;
	
	@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();
		//非标准的检测项目
		List<Long> sampleEntrustUnStandardProjectIdList = sampleTaskAssignContext.getSampleEntrustUnStandardProjectIdList();
		List<BusinessSampleEntrustUnStandardProjectExtendRespVO> businessSampleEntrustUnStandardProjectExtendList = businessSampleEntrustUnStandardProjectMapper.selectExtendByIds(sampleEntrustUnStandardProjectIdList);
		//根据子样分组
		Map<Long, List<BusinessSampleEntrustUnStandardProjectExtendRespVO>> businessSampleEntrustUnStandardProjectExtendMap = businessSampleEntrustUnStandardProjectExtendList.stream().collect(Collectors.groupingBy(BusinessSampleEntrustUnStandardProjectExtendRespVO::getBusinessSubSampleId));
		Set<Long> businessSubSampleIdList = businessSampleEntrustUnStandardProjectExtendMap.keySet();
		//查询子样
		List<BusinessSubSampleDO> businessSubSampleList = businessSubSampleMapper.selectByIds(businessSubSampleIdList);
		sampleTaskAssignContext.setBusinessSubSampleList(businessSubSampleList);
		
		//保存任务分配单
		List<BusinessAssayTaskDO> saveBusinessAssayTaskList = new ArrayList<>();
		//更新任务分配单
		List<BusinessAssayTaskDO> updateBusinessAssayTaskList = new ArrayList<>();
		//任务分配单明细
		List<BusinessAssayTaskDetailDO> businessAssayTaskDetailList = new ArrayList<>();
		
		//分样判定
		List<BusinessSubParentSampleAssessmentDO> saveBusinessSubParentSampleAssessmentList = new ArrayList<>();
		
		//子样判定
		List<BusinessSubSampleAssessmentDO> saveBusinessSubSampleAssessmentList = new ArrayList<>(); 
		
		//子样分析任务
		List<BusinessAssayTaskDataDO> saveBusinessAssayTaskDataList = new ArrayList<>();
		//子样分析任务参数
		List<BusinessAssayTaskParameterDataDO> saveBusinessAssayTaskParameterDataList = new ArrayList<>();
		//子样分析任务检测项目
		List<BusinessAssayProjectDataDO> saveBusinessAssayProjectDataList = new ArrayList<>(); 
		//子样分析任务检测项目参数
		List<BusinessAssayParameterDataDO> saveBusinessAssayParameterDataList = new ArrayList<>();
		
		List<BusinessSampleEntrustUnStandardProjectDO> saveBusinessSampleEntrustUnStandardProjectList = new ArrayList<>();
		List<BusinessSampleEntrustUnStandardProjectDO> updateBusinessSampleEntrustUnStandardProjectList = new ArrayList<>();
		
		// 用于缓存已处理的任务单，避免同一用户在同一业务类型下重复查询数据库
	    // Key: userId + dictionaryBusinessId, Value: BusinessAssayTaskDO
	    Map<String, BusinessAssayTaskDO> existingTaskCache = new HashMap<>();
		
		//循环
		for (Map.Entry<Long, List<BusinessSampleEntrustUnStandardProjectExtendRespVO>> businessSampleEntrustUnStandardProjectEntry : businessSampleEntrustUnStandardProjectExtendMap.entrySet()) {
			Long currBusinessSubSampleId = businessSampleEntrustUnStandardProjectEntry.getKey();
			List<BusinessSampleEntrustUnStandardProjectExtendRespVO> currBusinessSampleEntrustUnStandardProjectExtendList = businessSampleEntrustUnStandardProjectEntry.getValue();
			//分析的检测项目id
			List<Long> dictionaryProjectIdList = currBusinessSampleEntrustUnStandardProjectExtendList.stream().map(m -> m.getDictionaryProjectId()).distinct().collect(Collectors.toList());
			
			//分析项目
			String assayProject = currBusinessSampleEntrustUnStandardProjectExtendList.stream().map(m -> m.getDictionaryProjectShowName()).distinct().collect(Collectors.joining(","));
			
			//当前子样
			BusinessSubSampleDO currBusinessSubSampleDO = businessSubSampleList.stream().filter(f -> currBusinessSubSampleId.equals(f.getId())).findFirst().orElse(null);
			
			//分样判定
			BusinessSubParentSampleAssessmentDO businessSubParentSampleAssessmentDO = businessSubParentSampleAssessmentMapper.selectByBusinessSubParentSampleIdAndConfigAssayMethodIdAndRetestCount(currBusinessSubSampleDO.getBusinessSubParentSampleId(), assignConfigAssayMethodId, 0);
			if (businessSubParentSampleAssessmentDO == null) {
				businessSubParentSampleAssessmentDO = new BusinessSubParentSampleAssessmentDO();
				businessSubParentSampleAssessmentDO.setId(IdWorker.getId());
				businessSubParentSampleAssessmentDO.setBusinessSubParentSampleId(currBusinessSubSampleDO.getBusinessSubParentSampleId());
				businessSubParentSampleAssessmentDO.setConfigAssayMethodId(assignConfigAssayMethodId);
				businessSubParentSampleAssessmentDO.setAssayType(assayType);
				businessSubParentSampleAssessmentDO.setTaskType("常规");
				saveBusinessSubParentSampleAssessmentList.add(businessSubParentSampleAssessmentDO);
			}
			
			//子样判定数据
			BusinessSubSampleAssessmentDO businessSubSampleAssessmentDO = businessSubSampleAssessmentMapper.selectByBusinessSubSampleIdAndConfigAssayMethodIdAndRetestCount(currBusinessSubSampleId, assignConfigAssayMethodId, 0);
			if (businessSubSampleAssessmentDO == null) {
				businessSubSampleAssessmentDO = new BusinessSubSampleAssessmentDO();
				businessSubSampleAssessmentDO.setId(IdWorker.getId());	
				businessSubSampleAssessmentDO.setBusinessBaseSampleId(currBusinessSubSampleDO.getBusinessBaseSampleId());
				businessSubSampleAssessmentDO.setBusinessSubParentSampleId(currBusinessSubSampleDO.getBusinessSubParentSampleId());
				businessSubSampleAssessmentDO.setBusinessSubSampleId(currBusinessSubSampleDO.getId());
				businessSubSampleAssessmentDO.setBusinessSubParentSampleAssessmentId(businessSubParentSampleAssessmentDO.getId());
				businessSubSampleAssessmentDO.setConfigAssayMethodId(assignConfigAssayMethodId);
				businessSubSampleAssessmentDO.setAssayType(assayType);
				businessSubSampleAssessmentDO.setTaskType("常规");
				
				saveBusinessSubSampleAssessmentList.add(businessSubSampleAssessmentDO);
			}
			
			//根据任务数循环
			for (int i = 0; i < assayTaskCount; i++) {
				
				//子样检测任务
				BusinessAssayTaskDataDO businessAssayTaskDataDO = new BusinessAssayTaskDataDO();
				businessAssayTaskDataDO.setId(IdWorker.getId());
				businessAssayTaskDataDO.setBusinessBaseSampleId(currBusinessSubSampleDO.getBusinessBaseSampleId());
				businessAssayTaskDataDO.setBusinessSubParentSampleId(currBusinessSubSampleDO.getBusinessSubParentSampleId());
				businessAssayTaskDataDO.setBusinessSubSampleId(currBusinessSubSampleDO.getId());
				businessAssayTaskDataDO.setBusinessSubSampleAssessmentId(businessSubSampleAssessmentDO.getId());
				businessAssayTaskDataDO.setConfigAssayMethodId(assignConfigAssayMethodId);
				businessAssayTaskDataDO.setAssayType(assayType);
				businessAssayTaskDataDO.setTaskType("常规");
				businessAssayTaskDataDO.setConfigSampleFlowId(currBusinessSubSampleDO.getConfigSampleFlowId());
				businessAssayTaskDataDO.setSampleFlowNodeKey(QmsCommonConstant.FLOW_NODE_ANALYSIS);
				businessAssayTaskDataDO.setSampleFlowNodeTime(currBusinessSubSampleDO.getSampleFlowNodeTime());
				businessAssayTaskDataDO.setAssayDepartmentId(configAssayMethodDO.getAssayDepartmentId());
				businessAssayTaskDataDO.setAssayDepartmentName(configAssayMethodDO.getAssayDepartmentName());
				businessAssayTaskDataDO.setAssayProject(assayProject);
				

	            // 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);
				
	            //添加分析任务
				saveBusinessAssayTaskDataList.add(businessAssayTaskDataDO);
				
				//子样检测任务参数
				for (ConfigAssayMethodParameterDO configAssayMethodParameterDO : configAssayMethodParameterDOList) {
					BusinessAssayTaskParameterDataDO 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());
					}
					
					saveBusinessAssayTaskParameterDataList.add(businessAssayTaskParameterDataDO);
				}
				
				
				//循环检测项目
				for (ConfigAssayMethodProjectExtendRespVO configAssayMethodProjectDO : configAssayMethodProjectList) {

					//如果当前分析方法的项目不在当前检测项目中，则跳出循环继续
					if (!dictionaryProjectIdList.contains(configAssayMethodProjectDO.getDictionaryProjectId())) {
						continue;
					}
					BusinessSampleEntrustUnStandardProjectExtendRespVO currBusinessSampleEntrustUnStandardProjectExtend = currBusinessSampleEntrustUnStandardProjectExtendList.stream().filter(f -> configAssayMethodProjectDO.getDictionaryProjectId().equals(f.getDictionaryProjectId())).findFirst().orElse(null);
					
					if (currBusinessSampleEntrustUnStandardProjectExtend.getBusinessAssayTaskDataId() != null) {
						BusinessSampleEntrustUnStandardProjectExtendRespVO otherBusinessSampleEntrustUnStandardProjectExtend = BeanUtil.copyProperties(currBusinessSampleEntrustUnStandardProjectExtend, BusinessSampleEntrustUnStandardProjectExtendRespVO.class);
						otherBusinessSampleEntrustUnStandardProjectExtend.setId(IdWorker.getId());
						otherBusinessSampleEntrustUnStandardProjectExtend.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
						otherBusinessSampleEntrustUnStandardProjectExtend.setTaskCount(assayTaskCount);
						otherBusinessSampleEntrustUnStandardProjectExtend.setIsAssignTasked(QmsCommonConstant.YES);
						saveBusinessSampleEntrustUnStandardProjectList.add(BeanUtil.copyProperties(otherBusinessSampleEntrustUnStandardProjectExtend, BusinessSampleEntrustUnStandardProjectDO.class));
					} else {
						currBusinessSampleEntrustUnStandardProjectExtend.setBusinessAssayTaskDataId(businessAssayTaskDataDO.getId());
						currBusinessSampleEntrustUnStandardProjectExtend.setTaskCount(assayTaskCount);
						currBusinessSampleEntrustUnStandardProjectExtend.setIsAssignTasked(QmsCommonConstant.YES);
						updateBusinessSampleEntrustUnStandardProjectList.add(BeanUtil.copyProperties(currBusinessSampleEntrustUnStandardProjectExtend, BusinessSampleEntrustUnStandardProjectDO.class));
					}
					
					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(currBusinessSampleEntrustUnStandardProjectExtend.getUsage());

					businessAssayProjectDataDO.setMinimumLimitValue(configAssayMethodProjectDO.getMinimumLimitValue());
					businessAssayProjectDataDO.setIsEnabled(1);
					businessAssayProjectDataDO.setIsNotAssessment(0);
					
					saveBusinessAssayProjectDataList.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());
						}

						saveBusinessAssayParameterDataList.add(businessAssayParameterDataDO);
					}
					
				}
				
				
			}
		}
		// 【可选优化】重新整理明细的排序号 (SortNo)，确保每个任务单内的明细是 1, 2, 3...
	    // 因为上面的循环是交叉写入的，可能导致同一个 taskId 的 sortNo 不连续 (如 1, 1, 2, 2...) 如果多个用户交替
	    // 实际上上面的逻辑中，同一个 taskId 是由同一个用户产生的，但因为是交叉循环，可能插入顺序是交错的。
	    // 最稳妥的方式是按 taskId 分组重排
	    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(saveBusinessSubParentSampleAssessmentList);
	    sampleTaskAssignContext.setSaveBusinessSubSampleAssessmentList(saveBusinessSubSampleAssessmentList);
	    
		sampleTaskAssignContext.setSaveBusinessAssayTaskList(saveBusinessAssayTaskList);
		sampleTaskAssignContext.setUpdateBusinessAssayTaskList(updateBusinessAssayTaskList);
		
		sampleTaskAssignContext.setSaveBusinessAssayTaskDataList(saveBusinessAssayTaskDataList);
		sampleTaskAssignContext.setSaveBusinessAssayTaskParameterDataList(saveBusinessAssayTaskParameterDataList);
		sampleTaskAssignContext.setSaveBusinessAssayProjectDataList(saveBusinessAssayProjectDataList);
		sampleTaskAssignContext.setSaveBusinessAssayParameterDataList(saveBusinessAssayParameterDataList);
		sampleTaskAssignContext.setSaveBusinessSampleEntrustUnStandardProjectList(saveBusinessSampleEntrustUnStandardProjectList);
		sampleTaskAssignContext.setUpdateBusinessSampleEntrustUnStandardProjectList(updateBusinessSampleEntrustUnStandardProjectList);
		
		sampleTaskAssignContext.setBusinessAssayTaskDetailList(businessAssayTaskDetailList);
		
	}


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