package com.zt.plat.module.qms.thirdpartyapi.service;

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

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.JSONObject;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.module.qms.business.bus.controller.vo.*;
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.BusinessAssayTaskDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskParameterDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessQCManagementDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessQCManagementProjectDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessQCManagementSampleParameterDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustDetailDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessXRFDataDO;
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.BusinessAssayTaskParameterDataMapper;
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.BusinessQCManagementProjectDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessQCManagementSampleParameterDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustDetailMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessXRFDataMapper;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodConfInfo;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodConfItem;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodConfPoint;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigSubSampleMethodExtendRespVO;
import com.zt.plat.module.qms.business.config.dal.dataobject.BaseSampleDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigAssayMethodProjectDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigXRFConversionRateDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigXRFLineDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigXRFProjectDO;
import com.zt.plat.module.qms.business.config.dal.mapper.BaseSampleMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigAssayMethodProjectMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigSubSampleMethodMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigXRFConversionRateMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigXRFLineMapper;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigXRFProjectMapper;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.qms.thirdpartyapi.controller.vo.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class XRFDataServiceImpl implements XRFDataService {
	
	@Resource
	private ConfigXRFLineMapper configXRFLineMapper;
	
	@Resource
	private ConfigXRFProjectMapper configXRFProjectMapper;
	
	@Resource
	private ConfigXRFConversionRateMapper configXRFConversionRateMapper;
	
	@Resource
	private ConfigAssayMethodProjectMapper configAssayMethodProjectMapper;
	
	@Resource
	private ConfigSubSampleMethodMapper configSubSampleMethodMapper;
	
	@Resource
	private BusinessXRFDataMapper businessXRFDataMapper;
	
	@Resource
	private BaseSampleMapper baseSampleMapper;
	
	@Resource
	private BusinessSampleEntrustDetailMapper businessSampleEntrustDetailMapper;
	
	@Resource
	private BusinessAssayTaskDataMapper businessAssayTaskDataMapper;
	
	@Resource
	private BusinessAssayTaskParameterDataMapper businessAssayTaskParameterDataMapper;
	
	@Resource
	private BusinessAssayProjectDataMapper businessAssayProjectDataMapper;
	
	@Resource
	private BusinessAssayParameterDataMapper businessAssayParameterDataMapper;
	
	@Resource
	private BusinessQCManagementDataMapper businessQCManagementDataMapper;
	
	@Resource
	private BusinessQCManagementProjectDataMapper businessQCManagementProjectDataMapper;
	
	@Resource
	private BusinessQCManagementSampleParameterDataMapper businessQCManagementSampleParameterDataMapper;
	
	@Resource
	private BusinessQCCoefficientDataMapper businessQCCoefficientDataMapper;
	
	@Resource
	private BusinessQCCoefficientParameterDataMapper businessQCCoefficientParameterDataMapper;

	@Override
	public List<ConfigXRFLineCustomRespVO> getXrfLineList(String deviceNo) {
		List<ConfigXRFLineDO> list = configXRFLineMapper.selectByDeviceNo(deviceNo);
		return BeanUtils.toBean(list, ConfigXRFLineCustomRespVO.class);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int submitXrfData(List<XRFDeviceSampleReqVO> reqList) {
		Map<String, List<XRFDeviceSampleReqVO>> reqLineMap = reqList.stream().collect(Collectors.groupingBy(XRFDeviceSampleReqVO::getLineName));
		for (Map.Entry<String, List<XRFDeviceSampleReqVO>> entry : reqLineMap.entrySet()) {
			String lineName = entry.getKey();
			List<XRFDeviceSampleReqVO> xrfDeviceSampleList = entry.getValue();
			XRFDeviceSampleReqVO xrfDeviceSampleFirst = xrfDeviceSampleList.get(0);
			
	        //获取最大时间
	        LocalDateTime maxSampleTime = xrfDeviceSampleList.stream().max(Comparator.comparing(XRFDeviceSampleReqVO::getSampleTime)).map(XRFDeviceSampleReqVO::getSampleTime).get();

	        //获取荧光样品id列表
	        List<String> sampleIdList = xrfDeviceSampleList.stream().map(XRFDeviceSampleReqVO::getSampleId).collect(Collectors.toList());
	        
	        //获取荧光样品编号列表
	        List<String> sampleCodeList = xrfDeviceSampleList.stream().map(m -> m.getSampleCode()).collect(Collectors.toList());
	        
	        //查询数据库是否已保存了荧光数据
	        BusinessXRFDataReqVO existXRFDataSearch = new BusinessXRFDataReqVO();
	        existXRFDataSearch.setDeviceNo(xrfDeviceSampleFirst.getDeviceNo());
	        existXRFDataSearch.setLineName(lineName);
	        existXRFDataSearch.setXRFSampleIdList(sampleIdList);
	        List<BusinessXRFDataDO> existBusYgDataList = businessXRFDataMapper.selectList(existXRFDataSearch);
	        //已存在数据库中的样品id
	        List<String> existSampleIdList = new ArrayList<>();
	        for (BusinessXRFDataDO qmsBusYgData : existBusYgDataList) {
	            existSampleIdList.add(qmsBusYgData.getXRFSampleId());
	        }
	        //根据设备编号查询荧光元素配置
	        List<ConfigXRFProjectDO> conYgElementList = configXRFProjectMapper.selectByDeviceNo(xrfDeviceSampleFirst.getDeviceNo());
	        
	        //根据样品编号及分析方法类型，获取检测任务数据
	        List<BusinessAssayTaskDataExtendRespVO> businessAssayTaskDataList = businessAssayTaskDataMapper.selectBySampleAssayCodesAndConfigAssayMethodDictionaryBusinessKey(sampleCodeList, "xshxyggpf");

	        List<Long> businessAssayTaskDataIdList = businessAssayTaskDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
	        //获取检测参数
	        List<BusinessAssayTaskParameterDataExtendRespVO> businessAssayTaskParameterDataExtendList = new ArrayList<>();
	        if (CollUtil.isNotEmpty(businessAssayTaskDataIdList)) {
	        	businessAssayTaskParameterDataExtendList = businessAssayTaskParameterDataMapper.selectExtendByBusinessAssayTaskDataIds(businessAssayTaskDataIdList);
			}
	        
	        
	        //管理样和标准样
	        List<BusinessQCManagementDataDO> businessQCManagementDataList = businessQCManagementDataMapper.selectBySampleAssayCodesAndConfigAssayMethodDictionaryBusinessKey(sampleCodeList, "xshxyggpf");
	        List<Long> businessQCManagementDataIdList = businessQCManagementDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
	        //获取管理样和标准样的检测参数
	        List<BusinessQCManagementSampleParameterDataExtendRespVO> businessQCManagementSampleParameterDataExtendList = new ArrayList<>();
	        if (CollUtil.isNotEmpty(businessQCManagementDataIdList)) {
				businessQCManagementSampleParameterDataExtendList = businessQCManagementSampleParameterDataMapper.selectExtendByBusinessQCManagementDataIds(businessQCManagementDataIdList);
			}
	        
	        //空白样和标样
//	        List<BusinessQCCoefficientDataDO> businessQCCoefficientDataList = businessQCCoefficientDataMapper.selectBySampleAssayCodesAndConfigAssayMethodDictionaryBusinessKey(sampleCodeList, "xshxyggpf");

	        List<BusinessAssayTaskDataDO> businessAssayTaskDataDOList = new ArrayList<>();
	        List<BusinessAssayTaskParameterDataDO> businessAssayTaskParameterDataList = new ArrayList<>();
	        List<BusinessAssayProjectDataDO> busElementValueList = new ArrayList<>();
	        
	        List<BusinessAssayParameterDataDO> updateBusinessAssayParameterDataList = new ArrayList<>();
	        
	        List<BusinessQCManagementProjectDataDO> busQcManageElementValueList = new ArrayList<>();
	        List<BusinessQCManagementSampleParameterDataDO> businessQCManagementSampleParameterDataList = new ArrayList<>();
//	        List<BusinessQCCoefficientParameterDataDO> busQccParameterValueList = new ArrayList<>();
	        List<BusinessXRFDataDO> busYgDataList = new ArrayList<>();
	        BusinessXRFDataDO busYgData = null;
	        for (XRFDeviceSampleReqVO ygDeviceSample : xrfDeviceSampleList) {
	            if (existSampleIdList.contains(ygDeviceSample.getSampleId())) {
	                continue;
	            }
	            //分析元素
	            List<XRFDeviceSampleProjectReqVO> sampleElements = ygDeviceSample.getSampleProjects();
	            if (sampleElements == null) {
					log.info("分析元素为空！", JSON.toJSONString(ygDeviceSample));
					continue;
				}
	            busYgData = new BusinessXRFDataDO();
	            busYgData.setDeviceNo(ygDeviceSample.getDeviceNo());
	            busYgData.setLineName(ygDeviceSample.getLineName());
	            busYgData.setXRFSampleId(ygDeviceSample.getSampleId());
	            busYgData.setSampleCode(ygDeviceSample.getSampleCode());
	            busYgData.setSampleTime(ygDeviceSample.getSampleTime());
	            busYgData.setSampleStartTime(ygDeviceSample.getSampleStartTime());
	            busYgData.setSampleEndTime(ygDeviceSample.getSampleEndTime());
	            busYgData.setAssayOperator(ygDeviceSample.getAssayOper());
	            busYgData.setIsCheckCreate(ygDeviceSample.getIsCheck() ? 1 : 0);

				JSONObject assayDataJson = new JSONObject();
				String assayData = busYgData.getAssayData();
				if (StringUtils.isNotBlank(assayData)) {
					assayDataJson = JSON.parseObject(assayData);
				}
	            
	            
	            //处理匹配
				//a. 分析样
	            List<BusinessAssayProjectDataExtendRespVO> tempBusElementValueList = new ArrayList<>();
	            List<BusinessAssayTaskDataExtendRespVO> currBusinessAssayTaskDataList = businessAssayTaskDataList.stream().filter(f -> ygDeviceSample.getSampleCode().equals(f.getSampleAssayCode())).collect(Collectors.toList());//平行样情况，是列表
	            if (currBusinessAssayTaskDataList != null && currBusinessAssayTaskDataList.size() > 0) {
	            	for (BusinessAssayTaskDataExtendRespVO businessAssayTaskData : currBusinessAssayTaskDataList) {	            		
	            		//处理任务参数
		            	List<BusinessAssayTaskParameterDataExtendRespVO> currBusinessAssayTaskParameterDataExtendList = businessAssayTaskParameterDataExtendList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId())).collect(Collectors.toList());
		            	for (BusinessAssayTaskParameterDataExtendRespVO currBusinessAssayTaskParameterDataExtend : currBusinessAssayTaskParameterDataExtendList) {
							switch (currBusinessAssayTaskParameterDataExtend.getKey()) {
							case "lineName": 
								currBusinessAssayTaskParameterDataExtend.setValue(busYgData.getLineName());
								businessAssayTaskParameterDataList.add(BeanUtils.toBean(currBusinessAssayTaskParameterDataExtend, BusinessAssayTaskParameterDataDO.class)); 
								break;
							case "sampleStartTime": 
								currBusinessAssayTaskParameterDataExtend.setValue(DateUtil.formatLocalDateTime(busYgData.getSampleStartTime()));
								businessAssayTaskParameterDataList.add(BeanUtils.toBean(currBusinessAssayTaskParameterDataExtend, BusinessAssayTaskParameterDataDO.class)); 
								break;
							case "sampleEndTime":  
								currBusinessAssayTaskParameterDataExtend.setValue(DateUtil.formatLocalDateTime(busYgData.getSampleEndTime()));
								businessAssayTaskParameterDataList.add(BeanUtils.toBean(currBusinessAssayTaskParameterDataExtend, BusinessAssayTaskParameterDataDO.class)); 
								break;
							}
						}
	            		
		            	List<BusinessAssayProjectDataExtendRespVO> busElementValues = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataId(businessAssayTaskData.getId());
		                tempBusElementValueList.addAll(busElementValues);
					}
	            }
	            //b. 管理样和标准样
	            List<BusinessQCManagementProjectDataDO> tempBusinessQCManagementProjectDataList = new ArrayList<>();
	            List<BusinessQCManagementDataDO> currBusinessQCManagementDataList = businessQCManagementDataList.stream().filter(f -> ygDeviceSample.getSampleCode().equals(f.getSampleCode())).collect(Collectors.toList());
	            if (currBusinessQCManagementDataList != null && currBusinessQCManagementDataList.size() > 0) {
	            	for (BusinessQCManagementDataDO businessQCManagementData : currBusinessQCManagementDataList) {
	            		//处理任务参数
		            	List<BusinessQCManagementSampleParameterDataExtendRespVO> currBusinessQCManagementSampleParameterDataExtendList = businessQCManagementSampleParameterDataExtendList.stream().filter(f -> f.getBusinessQCManagementDataId().equals(businessQCManagementData.getId())).collect(Collectors.toList());
		            	for (BusinessQCManagementSampleParameterDataExtendRespVO currBusinessQCManagementSampleParameterDataExtend : currBusinessQCManagementSampleParameterDataExtendList) {
							switch (currBusinessQCManagementSampleParameterDataExtend.getKey()) {
							case "lineName": 
								currBusinessQCManagementSampleParameterDataExtend.setValue(busYgData.getLineName());
								businessQCManagementSampleParameterDataList.add(BeanUtils.toBean(currBusinessQCManagementSampleParameterDataExtend, BusinessQCManagementSampleParameterDataDO.class)); 
								break;
							case "sampleStartTime": 
								currBusinessQCManagementSampleParameterDataExtend.setValue(DateUtil.formatLocalDateTime(busYgData.getSampleStartTime()));
								businessQCManagementSampleParameterDataList.add(BeanUtils.toBean(currBusinessQCManagementSampleParameterDataExtend, BusinessQCManagementSampleParameterDataDO.class)); 
								break;
							case "sampleEndTime":  
								currBusinessQCManagementSampleParameterDataExtend.setValue(DateUtil.formatLocalDateTime(busYgData.getSampleEndTime()));
								businessQCManagementSampleParameterDataList.add(BeanUtils.toBean(currBusinessQCManagementSampleParameterDataExtend, BusinessQCManagementSampleParameterDataDO.class)); 
								break;
							}
						}
	            		
	            		
		            	List<BusinessQCManagementProjectDataDO> businessQCManagementProjectDataList = businessQCManagementProjectDataMapper.selectByBusinessQCManagementDataId(businessQCManagementData.getId());
		            	tempBusinessQCManagementProjectDataList.addAll(businessQCManagementProjectDataList);
					}
				}
	            //c. 空白样和标样
//	            List<BusinessQCCoefficientParameterDataDO> tempBusinessQCCoefficientParameterDataList = new ArrayList<>();
//	            List<BusinessQCCoefficientDataDO> currBusinessQCCoefficientDataList = businessQCCoefficientDataList.stream().filter(f -> ygDeviceSample.getSampleCode().equals(f.getSampleCode())).collect(Collectors.toList());
//	            if (currBusinessQCCoefficientDataList != null && currBusinessQCCoefficientDataList.size() > 0) {
//					for (BusinessQCCoefficientDataDO businessQCCoefficientDataDO : currBusinessQCCoefficientDataList) {
//						List<BusinessQCCoefficientParameterDataDO> businessQCCoefficientParameterDataList = businessQCCoefficientParameterDataMapper.selectByBusinessQCCoefficientDataId(businessQCCoefficientDataDO.getId());
//						tempBusinessQCCoefficientParameterDataList.addAll(businessQCCoefficientParameterDataList);
//					}
//				}

	            //分析元素
	            for (XRFDeviceSampleProjectReqVO ygDeviceSampleElement : sampleElements) {
	            	
	            	//如果设备上来的元素值为空，则跳过继续
	            	if (ygDeviceSampleElement.getXrfProjectValue() == null) {
						continue;
					}
	            	
	                //查询是否有特殊转换率
	            	ConfigXRFConversionRateDO conYgConverRate = configXRFConversionRateMapper.selectBy(ygDeviceSample.getDeviceNo(), ygDeviceSample.getLineName(), ygDeviceSampleElement.getXrfProjectName());
	                
	                ConfigXRFProjectDO conYgElement = null;
	                if(conYgConverRate != null && conYgConverRate.getConversionRate() != null) {
	                    conYgElement = conYgElementList.stream().filter(f -> f.getXRFProjectName().equals(ygDeviceSampleElement.getXrfProjectName()) && f.getConversionRate().equals(conYgConverRate.getConversionRate())).findFirst().orElse(null);
	                } else {
	                    conYgElement = conYgElementList.stream().filter(f -> f.getXRFProjectName().equals(ygDeviceSampleElement.getXrfProjectName()) && (StringUtils.isBlank(f.getXRFProjectUnit()) || StringUtils.isBlank(ygDeviceSampleElement.getXrfProjectUnit()) || f.getXRFProjectUnit().equals(ygDeviceSampleElement.getXrfProjectUnit()))).findFirst().orElse(null);
	                }
	                if(conYgElement != null) {
	                    //数据转换
	                    BigDecimal elementValue = BigDecimal.ZERO; 
	                    Integer conYgElementDataType = 0;
	                    if(conYgConverRate != null && conYgConverRate.getConversionRate() != null) {
	                        BigDecimal convertRate = new BigDecimal(conYgConverRate.getConversionRate().toString());
	                        elementValue = new BigDecimal(ygDeviceSampleElement.getXrfProjectValue()).multiply(convertRate);
	                    } else {
	                        BigDecimal convertRate = new BigDecimal(conYgElement.getConversionRate().toString());
	                        elementValue = new BigDecimal(ygDeviceSampleElement.getXrfProjectValue()).multiply(convertRate);
	                    }
	                    if(elementValue.compareTo(BigDecimal.ZERO) < 0) {
	                        elementValue = BigDecimal.ZERO;
	                    }
	                    if(conYgElement.getDataType() != null && "decimal".equals(conYgElement.getDataType())) {
	                        conYgElementDataType = conYgElement.getDecimalPosition(); 
	                    }
	                    Long elementId = conYgElement.getDictionaryProjectId();
	                    List<BusinessAssayProjectDataExtendRespVO> currBusElementValueList = tempBusElementValueList.stream().filter(f -> f.getDictionaryProjectId().equals(elementId) && f.getIsEnabled().equals(1)).collect(Collectors.toList());
	                    String symbol = "=";
	                    String minimumLimitValue = "";
	                    if (currBusElementValueList != null && currBusElementValueList.size() > 0) {
	                    	for (BusinessAssayProjectDataExtendRespVO busElementValue : currBusElementValueList) {
		                        //化验数据小数精度四舍六入五单双
		                        if("decimal".equals(busElementValue.getDataType())) {
		                            busElementValue.setValue(elementValue.setScale(busElementValue.getDecimalPosition(), RoundingMode.HALF_EVEN).toPlainString());
		                            if (elementValue.compareTo(new BigDecimal(busElementValue.getMinimumLimitValue())) < 0) {
		                            	symbol = "<";
		                            	minimumLimitValue = busElementValue.getMinimumLimitValue();
		                            	busElementValue.setValue(busElementValue.getMinimumLimitValue());
									}
									busElementValue.setSymbol(symbol);
		                            
		                        } else {
		                            busElementValue.setValue(elementValue.setScale(conYgElementDataType, RoundingMode.HALF_EVEN).toPlainString());
		                        }
		                        busElementValue.setRemark(conYgElement.getShowName() + ": " + busElementValue.getValue());
		                        busElementValueList.add(BeanUtils.toBean(busElementValue, BusinessAssayProjectDataDO.class));
								
							}
	                    }
	                    
	                    List<BusinessQCManagementProjectDataDO> currBusQcElementValueList = tempBusinessQCManagementProjectDataList.stream().filter(f -> f.getDictionaryProjectId().equals(elementId) && f.getIsEnabled().equals(1)).collect(Collectors.toList());
	                    if (currBusQcElementValueList != null && currBusQcElementValueList.size() > 0) {
							for (BusinessQCManagementProjectDataDO busElementValue : currBusQcElementValueList) {
		                        //化验数据小数精度四舍六入五单双
		                        if("decimal".equals(busElementValue.getDataType())) {
		                            busElementValue.setValue(elementValue.setScale(busElementValue.getDecimalPosition(), RoundingMode.HALF_EVEN).toPlainString());
		                            ConfigAssayMethodProjectDO configAssayMethodProjectDO = configAssayMethodProjectMapper.selectById(busElementValue.getConfigAssayMethodProjectId());
		                            if (elementValue.compareTo(new BigDecimal(configAssayMethodProjectDO.getMinimumLimitValue())) < 0) {
		                            	symbol = "<";
		                            	minimumLimitValue = configAssayMethodProjectDO.getMinimumLimitValue();
		                            	busElementValue.setValue(configAssayMethodProjectDO.getMinimumLimitValue());
									}
		                            busElementValue.setSymbol(symbol);
		                        } else {
		                            busElementValue.setValue(elementValue.setScale(conYgElementDataType, RoundingMode.HALF_EVEN).toPlainString());
		                        }
		                        busElementValue.setRemark(conYgElement.getShowName() + ": " + busElementValue.getValue());
		                        busQcManageElementValueList.add(busElementValue);
							}
						}
	                    	                    
	                    
		            	ReportFieldValueData reportFieldValueData = new ReportFieldValueData();
						reportFieldValueData.setFieldName(conYgElement.getSaveColumn());
						reportFieldValueData.setFieldValue(elementValue.setScale(conYgElementDataType, RoundingMode.HALF_EVEN).toPlainString());
						reportFieldValueData.setDecimalPosition(ygDeviceSampleElement.getValueDecimals());
						reportFieldValueData.setMathSymbol(symbol);
						if ("<".equals(symbol)) {
							reportFieldValueData.setFieldValue(minimumLimitValue);
						}
						reportFieldValueData.setUnit(ygDeviceSampleElement.getXrfProjectUnit());
						assayDataJson.put(conYgElement.getSaveColumn(), reportFieldValueData);
						
	                } 
	            }
	            //循环元素修改
	            for (BusinessAssayProjectDataExtendRespVO busElementValue : tempBusElementValueList) {
	            	boolean match = busElementValueList.stream().anyMatch(m -> m.getId().equals(busElementValue.getId()));
					if (!match) {//已经添加过的，不再添加
						busElementValueList.add(BeanUtils.toBean(busElementValue, BusinessAssayProjectDataDO.class));
					}
				}
	            
	            //设置分析数据
	            busYgData.setAssayData(assayDataJson.toJSONString());
	            
	            if (currBusinessAssayTaskDataList != null && currBusinessAssayTaskDataList.size() > 0) {
	            	for (BusinessAssayTaskDataExtendRespVO businessAssayTaskData : currBusinessAssayTaskDataList) {
	            		
	            		//查询当前子样方法配置
	            		ConfigSubSampleMethodExtendRespVO configSubSampleMethod = configSubSampleMethodMapper.selectByConfigSubSampleIdAndConfigAssayMethodId(businessAssayTaskData.getConfigSubSampleId(), businessAssayTaskData.getConfigAssayMethodId());
	            		//扩展配置
	                	String configInfomation = configSubSampleMethod.getConfigInfomation();
	                	if (StringUtils.isNotBlank(configInfomation)) {
	                		//解析配置
	        				ConfigSubSampleMethodConfInfo configSubSampleMethodConfInfo = JSON.parseObject(configInfomation, ConfigSubSampleMethodConfInfo.class);
	        				//当前要设置到的参数
	        				List<ConfigSubSampleMethodConfItem> setParamList = configSubSampleMethodConfInfo.getSetParam();
	        				if (CollUtil.isNotEmpty(setParamList)) {//参数不为空，则设置
	        					//方法key
		        				String methodKey = setParamList.stream().map(m -> m.getTarget().getMethodKey()).distinct().findFirst().orElse(null);
		        				
								//1 查询委托明细
								BusinessSampleEntrustDetailDO businessSampleEntrustDetailDO = businessSampleEntrustDetailMapper.selectByBusinessBaseSampleId(businessAssayTaskData.getBusinessBaseSampleId());
								//2 查询样品大类
								BaseSampleDO baseSampleDO = baseSampleMapper.selectById(businessSampleEntrustDetailDO.getBaseSampleId());
								
								//3 判断样品大类类型
								if (QmsCommonConstant.ENTRUST_INSPECTION_ANALYSIS_SAMPLE.equals(baseSampleDO.getDictionaryBusinessKey())) {//如果是商检分析样
									//委托登记Id
									Long businessSampleEntrustRegistrationId = businessSampleEntrustDetailDO.getBusinessSampleEntrustRegistrationId();
									//查询委托登记明细
									List<BusinessSampleEntrustDetailDO> businessSampleEntrustDetailList  = businessSampleEntrustDetailMapper.selectByBusinessSampleEntrustRegistrationId(businessSampleEntrustRegistrationId);
									//获取主样Id列表
									List<Long> businessBaseSampleIdList = businessSampleEntrustDetailList.stream().map(m -> m.getBusinessBaseSampleId()).collect(Collectors.toList());
									//查询当前分析方法下对应的任务
			        				List<BusinessAssayTaskDataDO> targetBusinessAssayTaskDataList = businessAssayTaskDataMapper.selectByBusinessBaseSampleIdsAndMethodKey(businessBaseSampleIdList, methodKey);
			        				List<Long> targetBusinessAssayTaskDataIdList = targetBusinessAssayTaskDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
			        				List<BusinessAssayProjectDataExtendRespVO> targetBusinessAssayProjectDataExtendList = new ArrayList<>();
			        				if (CollUtil.isNotEmpty(targetBusinessAssayTaskDataIdList)) {
			        					targetBusinessAssayProjectDataExtendList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(targetBusinessAssayTaskDataIdList);
									}
			        				
			        				for (ConfigSubSampleMethodConfItem configSubSampleMethodConfItem : setParamList) {
			        					ConfigSubSampleMethodConfPoint source = configSubSampleMethodConfItem.getSource();
			        					String project = source.getProject();
			        					BusinessAssayProjectDataExtendRespVO currentBusinessAssayProjectData = tempBusElementValueList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId()) && project.equals(f.getSimpleName())).findFirst().orElse(null);
			        					if (currentBusinessAssayProjectData == null) {
											continue;
										}
			        					ConfigSubSampleMethodConfPoint target = configSubSampleMethodConfItem.getTarget();
			        					for (BusinessAssayTaskDataDO targetBusinessAssayTaskData : targetBusinessAssayTaskDataList) {
			        						if (StringUtils.isNotBlank(target.getProject())) {//检测项目参数赋值
				        						List<String> targetProjectList = Arrays.asList(target.getProject().split(","));
				        						String targetParameter = target.getParameter();
				        						for (String targetProject : targetProjectList) {
				        							BusinessAssayProjectDataExtendRespVO targetBusinessAssayProjectData = targetBusinessAssayProjectDataExtendList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(targetBusinessAssayTaskData.getId()) && targetProject.equals(f.getSimpleName())).findFirst().orElse(null);
				        							if (targetBusinessAssayProjectData == null) {
														continue;
													}
				        							BusinessAssayParameterDataDO businessAssayParameterDataDO = businessAssayParameterDataMapper.selectByBusinessAssayProjectDataIdAndProjectSimpleNameAndParameterKey(targetBusinessAssayProjectData.getId(), targetProject, targetParameter);
				        							if (businessAssayParameterDataDO != null) {
				        								businessAssayParameterDataDO.setValue(currentBusinessAssayProjectData.getValue());
				        								updateBusinessAssayParameterDataList.add(businessAssayParameterDataDO);
				        							}
				        							
				        						}
											} else if (StringUtils.isNotBlank(target.getAttribute())) {//分析任务属性赋值
												BusinessAssayTaskParameterDataDO businessAssayTaskParameterDataDO = businessAssayTaskParameterDataMapper.selectByBusinessAssayTaskDataIdAndKey(targetBusinessAssayTaskData.getId(), target.getAttribute());
												if (businessAssayTaskParameterDataDO != null) {
													businessAssayTaskParameterDataDO.setValue(currentBusinessAssayProjectData.getValue());
													businessAssayTaskParameterDataList.add(businessAssayTaskParameterDataDO);
												}
												
											}
			        						
			        					}
			        				}
								} else if (QmsCommonConstant.ENTRUST_COMPREHENSIVE_INSPECTION_SAMPLE.equals(baseSampleDO.getDictionaryBusinessKey())) {//如果是商检综合样
									//查询当前分析方法下对应的任务
			        				List<BusinessAssayTaskDataDO> targetBusinessAssayTaskDataList = businessAssayTaskDataMapper.selectByBusinessSubSampleIdAndMethodKey(businessAssayTaskData.getBusinessSubSampleId(), methodKey);
			        				List<Long> targetBusinessAssayTaskDataIdList = targetBusinessAssayTaskDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
			        				List<BusinessAssayProjectDataExtendRespVO> targetBusinessAssayProjectDataExtendList = new ArrayList<>();
			        				if (CollUtil.isNotEmpty(targetBusinessAssayTaskDataIdList)) {
			        					targetBusinessAssayProjectDataExtendList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(targetBusinessAssayTaskDataIdList);
									}
			        				
			        				for (ConfigSubSampleMethodConfItem configSubSampleMethodConfItem : setParamList) {
			        					ConfigSubSampleMethodConfPoint source = configSubSampleMethodConfItem.getSource();
			        					String project = source.getProject();
			        					BusinessAssayProjectDataExtendRespVO currentBusinessAssayProjectData = tempBusElementValueList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId()) && project.equals(f.getSimpleName())).findFirst().orElse(null);
			        					if (currentBusinessAssayProjectData == null) {
											continue;
										}
			        					ConfigSubSampleMethodConfPoint target = configSubSampleMethodConfItem.getTarget();
			        					for (BusinessAssayTaskDataDO targetBusinessAssayTaskData : targetBusinessAssayTaskDataList) {
			        						if (StringUtils.isNotBlank(target.getProject())) {//检测项目参数赋值
				        						List<String> targetProjectList = Arrays.asList(target.getProject().split(","));
				        						String targetParameter = target.getParameter();
				        						for (String targetProject : targetProjectList) {
				        							BusinessAssayProjectDataExtendRespVO targetBusinessAssayProjectData = targetBusinessAssayProjectDataExtendList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(targetBusinessAssayTaskData.getId()) && targetProject.equals(f.getSimpleName())).findFirst().orElse(null);
				        							if (targetBusinessAssayProjectData == null) {
														continue;
													}
				        							BusinessAssayParameterDataDO businessAssayParameterDataDO = businessAssayParameterDataMapper.selectByBusinessAssayProjectDataIdAndProjectSimpleNameAndParameterKey(targetBusinessAssayProjectData.getId(), targetProject, targetParameter);
				        							if (businessAssayParameterDataDO != null) {
				        								businessAssayParameterDataDO.setValue(currentBusinessAssayProjectData.getValue());
				        								updateBusinessAssayParameterDataList.add(businessAssayParameterDataDO);
				        							}
				        							
				        						}
			        						} else if (StringUtils.isNotBlank(target.getAttribute())) {//分析任务属性赋值
												BusinessAssayTaskParameterDataDO businessAssayTaskParameterDataDO = businessAssayTaskParameterDataMapper.selectByBusinessAssayTaskDataIdAndKey(targetBusinessAssayTaskData.getId(), target.getAttribute());
												if (businessAssayTaskParameterDataDO != null) {
													businessAssayTaskParameterDataDO.setValue(currentBusinessAssayProjectData.getValue());
													businessAssayTaskParameterDataList.add(businessAssayTaskParameterDataDO);
												}
												
											}
			        					}
			        				}
								} else if (QmsCommonConstant.ENTRUST_COMMISSION_INSPECTION_SAMPLE.equals(baseSampleDO.getDictionaryBusinessKey())) {//如果是委检样
									//查询当前分析方法下对应的任务
			        				List<BusinessAssayTaskDataDO> targetBusinessAssayTaskDataList = businessAssayTaskDataMapper.selectByBusinessSubSampleIdAndMethodKey(businessAssayTaskData.getBusinessSubSampleId(), methodKey);
			        				List<Long> targetBusinessAssayTaskDataIdList = targetBusinessAssayTaskDataList.stream().map(m -> m.getId()).collect(Collectors.toList());
			        				List<BusinessAssayProjectDataExtendRespVO> targetBusinessAssayProjectDataExtendList = new ArrayList<>() ;
			        				if (CollUtil.isNotEmpty(targetBusinessAssayTaskDataIdList)) {
			        					targetBusinessAssayProjectDataExtendList = businessAssayProjectDataMapper.selectByBusinessAssayTaskDataIds(targetBusinessAssayTaskDataIdList);
									}
			        				
			        				for (ConfigSubSampleMethodConfItem configSubSampleMethodConfItem : setParamList) {
			        					ConfigSubSampleMethodConfPoint source = configSubSampleMethodConfItem.getSource();
			        					String project = source.getProject();
			        					BusinessAssayProjectDataExtendRespVO currentBusinessAssayProjectData = tempBusElementValueList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(businessAssayTaskData.getId()) && project.equals(f.getSimpleName())).findFirst().orElse(null);
			        					if (currentBusinessAssayProjectData == null) {
											continue;
										}
			        					ConfigSubSampleMethodConfPoint target = configSubSampleMethodConfItem.getTarget();
			        					for (BusinessAssayTaskDataDO targetBusinessAssayTaskData : targetBusinessAssayTaskDataList) {
			        						if (StringUtils.isNotBlank(target.getProject())) {//检测项目参数赋值
				        						List<String> targetProjectList = Arrays.asList(target.getProject().split(","));
				        						String targetParameter = target.getParameter();
				        						for (String targetProject : targetProjectList) {
				        							BusinessAssayProjectDataExtendRespVO targetBusinessAssayProjectData = targetBusinessAssayProjectDataExtendList.stream().filter(f -> f.getBusinessAssayTaskDataId().equals(targetBusinessAssayTaskData.getId()) && targetProject.equals(f.getSimpleName())).findFirst().orElse(null);
				        							if (targetBusinessAssayProjectData == null) {
														continue;
													}
				        							BusinessAssayParameterDataDO businessAssayParameterDataDO = businessAssayParameterDataMapper.selectByBusinessAssayProjectDataIdAndProjectSimpleNameAndParameterKey(targetBusinessAssayProjectData.getId(), targetProject, targetParameter);
				        							if (businessAssayParameterDataDO != null && StringUtils.isBlank(businessAssayParameterDataDO.getValue())) {//值为空，才赋值
				        								businessAssayParameterDataDO.setValue(currentBusinessAssayProjectData.getValue());
				        								updateBusinessAssayParameterDataList.add(businessAssayParameterDataDO);
				        							}
				        							
				        						}
			        						} else if (StringUtils.isNotBlank(target.getAttribute())) {//分析任务属性赋值
												BusinessAssayTaskParameterDataDO businessAssayTaskParameterDataDO = businessAssayTaskParameterDataMapper.selectByBusinessAssayTaskDataIdAndKey(targetBusinessAssayTaskData.getId(), target.getAttribute());
												if (businessAssayTaskParameterDataDO != null) {
													businessAssayTaskParameterDataDO.setValue(currentBusinessAssayProjectData.getValue());
													businessAssayTaskParameterDataList.add(businessAssayTaskParameterDataDO);
												}
												
											}
			        					}
			        				}
									
								}
	        				}
	        			}
	            		
		                busYgData.setIsMatched(QmsCommonConstant.YES);
		                busYgData.setBusinessBaseSampleId(businessAssayTaskData.getBusinessBaseSampleId());
		                busYgData.setBusinessSubParentSampleId(businessAssayTaskData.getBusinessSubParentSampleId());
		                busYgData.setBusinessSubSampleId(businessAssayTaskData.getBusinessSubSampleId());
		                busYgData.setBusinessAssayTaskDataId(businessAssayTaskData.getId());
		                businessAssayTaskDataDOList.add(BeanUtils.toBean(businessAssayTaskData, BusinessAssayTaskDataDO.class));
	            	}
	            }
	            if (currBusinessQCManagementDataList != null && currBusinessQCManagementDataList.size() > 0) {
	            	for (BusinessQCManagementDataDO businessQCManagementData : currBusinessQCManagementDataList) {
	            		busYgData.setBusinessQCManagementDataId(businessQCManagementData.getId());
	            		busYgData.setIsMatched(QmsCommonConstant.YES);
					}
	            }
	            
	            
	            busYgDataList.add(busYgData);
	        }
	        //查询荧光分析线配置
	        ConfigXRFLineDO conYgLine = configXRFLineMapper.selectByDeviceNoAndLineName(xrfDeviceSampleFirst.getDeviceNo(), lineName);
	        if (xrfDeviceSampleFirst.getIsCheck()) {
	            conYgLine.setLastCheckDataTime(maxSampleTime);
	        } else {
	            conYgLine.setLastSynchronousDataTime(maxSampleTime);
	        }
	        //更新荧光线配置时间
	        configXRFLineMapper.updateById(conYgLine);
	        if (busYgDataList.size() > 0) {
	           
	            //保存荧光数据
	            businessXRFDataMapper.insertBatch(busYgDataList);

	            //更新任务参数
	            if (businessAssayTaskParameterDataList.size() > 0) {
					businessAssayTaskParameterDataMapper.updateBatch(businessAssayTaskParameterDataList);
				}
	            
	            //更新分析结果
	            if (busElementValueList.size() > 0) {
	                businessAssayProjectDataMapper.updateBatch(busElementValueList);
	            }
	            
	            //更新检测项目参数
	            if (updateBusinessAssayParameterDataList.size() > 0) {
	            	businessAssayParameterDataMapper.updateBatch(updateBusinessAssayParameterDataList);
				}
	            
	            //荧光管理样和标准样
	            if (busQcManageElementValueList.size() > 0) {
					businessQCManagementProjectDataMapper.updateBatch(busQcManageElementValueList);
				}
	            if (businessQCManagementSampleParameterDataList.size() > 0) {
					businessQCManagementSampleParameterDataMapper.updateBatch(businessQCManagementSampleParameterDataList);
				}
	            //荧光空白样和标样
//	            if (busQccParameterValueList.size() > 0) {
//					businessQCCoefficientParameterDataMapper.updateBatch(busQccParameterValueList);
//				}
	        }
		}
		
		
		return reqList.size();
	}
	

}
