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

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
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.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.infra.api.businessfile.BusinessFileApi;
import com.zt.plat.module.infra.api.businessfile.dto.BusinessFileSaveReqDTO;
import com.zt.plat.module.infra.api.file.FileApi;
import com.zt.plat.module.infra.api.file.dto.FileCreateReqDTO;
import com.zt.plat.module.infra.api.file.dto.FileRespDTO;
import com.zt.plat.module.qms.business.bus.controller.vo.BusinessAssayReportDataExtendRespVO;
import com.zt.plat.module.qms.business.bus.controller.vo.BusinessSubParentSampleAssessmentProjectExtendRespVO;
import com.zt.plat.module.qms.business.bus.controller.vo.DeptEntrustDocAuditParam;
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.BusinessSampleEntrustDepartmentDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustDepartmentDetailDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustFileDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleEntrustRegistrationDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleAssessmentDO;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayReportDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskDataMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessAssayTaskMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustDepartmentDetailMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustDepartmentMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustFileMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSampleEntrustRegistrationMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubParentSampleAssessmentMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubParentSampleAssessmentProjectMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleAssessmentMapper;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigReportTemplateDO;
import com.zt.plat.module.qms.business.config.service.ConfigReportTemplateService;
import com.zt.plat.module.qms.business.reportdoc.service.ReportDocumentAssistService;
import com.zt.plat.module.qms.business.reportdoc.service.ReportDocumentDataService;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.qms.framework.gridreport.GridReport;
import com.zt.plat.module.qms.framework.gridreport.PdfHelper;
import com.zt.plat.module.qms.mq.SampleEntrustRegistrationAssayCompleteMessage;
import com.zt.plat.module.qms.mq.producer.SampleEntrustRegistrationAssayCompleteProducer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HtmlUtil;
import gridreport.jni.BinaryObject;
import gridreport.jni.ExportType;
import jakarta.annotation.Resource;

/**
 * 样品班组委托报告审核服务
 */
@Service
public class SampleDeptEntrustDocAuditServiceImpl implements SampleDeptEntrustDocAuditService {
	
	@Resource
	private BusinessSampleEntrustRegistrationMapper businessSampleEntrustRegistrationMapper;
	
	@Resource
	private BusinessSampleEntrustDepartmentMapper businessSampleEntrustDepartmentMapper;
	
	@Resource
	private BusinessSampleEntrustDepartmentDetailMapper businessSampleEntrustDepartmentDetailMapper;
	
	@Resource
	private BusinessSampleEntrustFileMapper businessSampleEntrustFileMapper;
	
	@Resource
	private BusinessAssayTaskDataMapper businessAssayTaskDataMapper;
	
	@Resource
	private BusinessAssayTaskMapper businessAssayTaskMapper;
	
	@Resource
	private BusinessSubSampleAssessmentMapper businessSubSampleAssessmentMapper;
	
	@Resource
	private BusinessSubParentSampleAssessmentMapper businessSubParentSampleAssessmentMapper;
	
	@Resource
	private BusinessSubParentSampleAssessmentProjectMapper businessSubParentSampleAssessmentProjectMapper;
	
	@Resource
	private BusinessAssayReportDataMapper businessAssayReportDataMapper;
	
	@Resource
	private SampleAnalysisAuditService sampleAnalysisAuditService;
	
	@Resource
	private ConfigReportTemplateService configReportTemplateService;

	@Resource
	private GridReport gridReport;
	
    @Resource 
    private FileApi fileApi;
    
    @Resource 
    private BusinessFileApi businessFileApi;
    
    @Resource 
    private ReportDocumentDataService reportDocumentDataService;
    
    @Resource
    private ReportDocumentAssistService reportDocumentAssistService;
	
	@Resource
	private SampleEntrustRegistrationAssayCompleteProducer sampleEntrustRegistrationAssayCompleteProducer;

	@Override
 	public JSONObject getDeptEntrustDocAuditByBusSampleEntrustDeptId(Long businessSampleEntrustDepartmentId) {
		JSONObject resultJsonObject = new JSONObject();
		BusinessSampleEntrustDepartmentDO businessSampleEntrustDepartmentDO = businessSampleEntrustDepartmentMapper.selectById(businessSampleEntrustDepartmentId);

        List<Map<String, Object>> columns = new ArrayList<>();
		String assayProject = businessSampleEntrustDepartmentDO.getAssayProject();
		String[] assayProjectSplit = assayProject.split(",");
		for (String project : assayProjectSplit) {
	    	columns.add(new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
			{
	    		put("title", project);
	    		put("field", HtmlUtil.cleanHtmlTag(project));
	    	}});
		}

//        Set<String> assayProjectAndUnitSet = new HashSet<>();
		
		JSONObject formData = new JSONObject();
        
        List<Map<String, Object>> datas = new ArrayList<>();
        
        //查询委托分析部门明细样品
		List<BusinessSampleEntrustDepartmentDetailDO> businessSampleEntrustDepartmentDetailDOList = businessSampleEntrustDepartmentDetailMapper.selectByBusinessSampleEntrustDepartmentId(businessSampleEntrustDepartmentId);
		//或者主样id列表
		List<Long> businessBaseSampleIdList = businessSampleEntrustDepartmentDetailDOList.stream().map(m -> m.getBusinessBaseSampleId()).collect(Collectors.toList());
		//查询分析任务
		List<BusinessAssayTaskDataDO> businessAssayTaskDataDOList = businessAssayTaskDataMapper.selectByBusinessBaseSampleIdsAndAssayDepartmentId(businessBaseSampleIdList, businessSampleEntrustDepartmentDO.getAssayDepartmentId());
		List<Long> businessSubSampleAssessmentIdList = businessAssayTaskDataDOList.stream().filter(f -> f.getBusinessSubSampleAssessmentId() != null).map(m -> m.getBusinessSubSampleAssessmentId()).distinct().collect(Collectors.toList());
		List<BusinessSubSampleAssessmentDO> businessSubSampleAssessmentDOList = businessSubSampleAssessmentMapper.selectByIds(businessSubSampleAssessmentIdList);
		List<Long> businessSubParentSampleAssessmentIdList = businessSubSampleAssessmentDOList.stream().filter(f -> f.getBusinessSubParentSampleAssessmentId() != null).map(m -> m.getBusinessSubParentSampleAssessmentId()).distinct().collect(Collectors.toList());
		List<BusinessSubParentSampleAssessmentProjectExtendRespVO> businessSubParentSampleAssessmentProjectList = businessSubParentSampleAssessmentProjectMapper.selectByBusinessSubParentSampleAssessmentIds(businessSubParentSampleAssessmentIdList);
		for (BusinessSampleEntrustDepartmentDetailDO businessSampleEntrustDepartmentDetailDO : businessSampleEntrustDepartmentDetailDOList) {
			Map<String, Object> businessSampleEntrustDepartmentDetailDOMap = BeanUtil.beanToMap(businessSampleEntrustDepartmentDetailDO);
			List<Long> currBusinessSubSampleAssessmentIdList = businessAssayTaskDataDOList.stream().filter(f -> f.getBusinessBaseSampleId().equals(businessSampleEntrustDepartmentDetailDO.getBusinessBaseSampleId())).map(m -> m.getBusinessSubSampleAssessmentId()).collect(Collectors.toList());
			List<Long> currBusinessSubParentSampleAssessmentIdList = businessSubSampleAssessmentDOList.stream().filter(f -> currBusinessSubSampleAssessmentIdList.contains(f.getId())).map(m -> m.getBusinessSubParentSampleAssessmentId()).distinct().collect(Collectors.toList());
			List<BusinessSubParentSampleAssessmentProjectExtendRespVO> currBusinessSubParentSampleAssessmentProjecList = businessSubParentSampleAssessmentProjectList.stream().filter(f -> currBusinessSubParentSampleAssessmentIdList.contains(f.getBusinessSubParentSampleAssessmentId()) ).collect(Collectors.toList());// && QmsCommonConstant.YES.equals(f.getIsReported())
			for (BusinessSubParentSampleAssessmentProjectExtendRespVO businessSubParentSampleAssessmentProject : currBusinessSubParentSampleAssessmentProjecList) {
				businessSampleEntrustDepartmentDetailDOMap.put(businessSubParentSampleAssessmentProject.getSimpleName(), businessSubParentSampleAssessmentProject.getAssessmentValue());
				businessSampleEntrustDepartmentDetailDOMap.put(businessSubParentSampleAssessmentProject.getSimpleName() + "_businessSubParentSampleId", businessSubParentSampleAssessmentProject.getBusinessSubParentSampleId());
				businessSampleEntrustDepartmentDetailDOMap.put(businessSubParentSampleAssessmentProject.getSimpleName() + "_configAssayMethodProjectId", businessSubParentSampleAssessmentProject.getConfigAssayMethodProjectId());
				
//				boolean isAddColumn = columns.stream().anyMatch(a -> businessSubParentSampleAssessmentProject.getSimpleName().equals(a.get("field")));
//				if (!isAddColumn) {
//					columns.add(new HashMap<String, Object>() {
//						private static final long serialVersionUID = 1L;
//					{
//			    		put("title", businessSubParentSampleAssessmentProject.getShowName() + "(" + businessSubParentSampleAssessmentProject.getDictionaryProjectUnit() + ")");
//			    		put("field", businessSubParentSampleAssessmentProject.getSimpleName());
//			    	}});
//				}
				
//				assayProjectAndUnitSet.add(businessSubParentSampleAssessmentProject.getSimpleName() + "(" + businessSubParentSampleAssessmentProject.getDictionaryProjectUnit() + ")");
			}
			datas.add(businessSampleEntrustDepartmentDetailDOMap);
		}

		Set<String> assayOperatorSet = new HashSet<>();
		//查询任务
		List<Long> businessAssayTaskIdList  = businessAssayTaskDataDOList.stream().map(m -> m.getBusinessAssayTaskId()).distinct().collect(Collectors.toList());
		List<BusinessAssayTaskDO> businessAssayTaskList = businessAssayTaskMapper.selectByIds(businessAssayTaskIdList);
		for (BusinessAssayTaskDO businessAssayTaskDO : businessAssayTaskList) {
			assayOperatorSet.add(businessAssayTaskDO.getAssayOperator());
		}
		BusinessSampleEntrustRegistrationDO businessSampleEntrustRegistrationDO = businessSampleEntrustRegistrationMapper.selectById(businessSampleEntrustDepartmentDO.getBusinessSampleEntrustRegistrationId());
		String sampleCategory = businessSampleEntrustRegistrationDO.getSampleCategory();
		String externalInfomation = businessSampleEntrustRegistrationDO.getExternalInfomation();
		if (StringUtils.isNotBlank(externalInfomation)) {
			JSONObject extInfoJsonObject = JSONObject.parseObject(externalInfomation);
			sampleCategory = extInfoJsonObject.getString("sampleCategory");
		}
		formData.put("assayOperator", CollUtil.join(assayOperatorSet, "、"));
		formData.put("sampleCategory", sampleCategory);
		formData.put("entrustCode", businessSampleEntrustRegistrationDO.getEntrustNumber());
		
		//查询报表数据
		List<BusinessAssayReportDataExtendRespVO> businessAssayReportDataList = businessAssayReportDataMapper.selectExtendByBusinessBaseSampleIds(businessBaseSampleIdList);
		
		resultJsonObject.put("columns", columns);
		resultJsonObject.put("datas", datas);
		resultJsonObject.put("assayProject", Arrays.asList(businessSampleEntrustDepartmentDO.getAssayProjectUnit().split(",")));
//		resultJsonObject.put("assayOperator", CollUtil.join(assayOperatorSet, "、"));
		resultJsonObject.put("formData", formData);
		resultJsonObject.put("businessAssayReportDataList", businessAssayReportDataList);
		
		return resultJsonObject;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void auditDeptEntrustDocAudit(DeptEntrustDocAuditParam param) {
		//当前登录用户昵称
		String nickName = SecurityFrameworkUtils.getLoginUserNickname();
		Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
		Long businessSampleEntrustDepartmentId = param.getBusinessSampleEntrustDepartmentId();
		BusinessSampleEntrustDepartmentDO businessSampleEntrustDepartmentDO = businessSampleEntrustDepartmentMapper.selectById(businessSampleEntrustDepartmentId);
		if (QmsCommonConstant.YES.equals(businessSampleEntrustDepartmentDO.getIsReported())) {
			throw new ServiceException(1_032_100_000, "当前商检报告已审核！");
		}
		
		businessSampleEntrustDepartmentDO.setIsReported(QmsCommonConstant.YES);
		businessSampleEntrustDepartmentDO.setReportOperator(nickName);
		businessSampleEntrustDepartmentDO.setReportOperatorId(loginUserId);
		businessSampleEntrustDepartmentDO.setReportTime(LocalDateTime.now());
		businessSampleEntrustDepartmentDO.setAssayStatus(QmsCommonConstant.CHECKED);
		
		Set<String> assayOperatorSet = new HashSet<>();
		Set<String> assayOperatorIdSet = new HashSet<>();
		
		List<BusinessSampleEntrustFileDO> businessSampleEntrustFileDOList = new ArrayList<>();

		BusinessSampleEntrustRegistrationDO businessSampleEntrustRegistrationDO = businessSampleEntrustRegistrationMapper.selectById(businessSampleEntrustDepartmentDO.getBusinessSampleEntrustRegistrationId());
		String sampleCategory = businessSampleEntrustRegistrationDO.getSampleCategory();
		String externalInfomation = businessSampleEntrustRegistrationDO.getExternalInfomation();
		if (StringUtils.isNotBlank(externalInfomation)) {
			JSONObject extInfoJsonObject = JSONObject.parseObject(externalInfomation);
			sampleCategory = extInfoJsonObject.getString("sampleCategory");
		}

        //查询委托分析部门明细样品
		List<BusinessSampleEntrustDepartmentDetailDO> businessSampleEntrustDepartmentDetailDOList = businessSampleEntrustDepartmentDetailMapper.selectByBusinessSampleEntrustDepartmentId(businessSampleEntrustDepartmentId);
		//主样id列表
		List<Long> businessBaseSampleIdList = businessSampleEntrustDepartmentDetailDOList.stream().map(m -> m.getBusinessBaseSampleId()).collect(Collectors.toList());
		//查询分析任务
		List<BusinessAssayTaskDataDO> businessAssayTaskDataDOList = businessAssayTaskDataMapper.selectByBusinessBaseSampleIdsAndAssayDepartmentId(businessBaseSampleIdList, businessSampleEntrustDepartmentDO.getAssayDepartmentId());
		Map<Long, List<BusinessAssayTaskDataDO>> businessAssayTaskDataByTaskMap = businessAssayTaskDataDOList.stream().collect(Collectors.groupingBy(BusinessAssayTaskDataDO::getBusinessAssayTaskId));
//		List<Long> businessAssayTaskIdList = businessAssayTaskDataDOList.stream().map(m -> m.getBusinessAssayTaskId()).distinct().collect(Collectors.toList());
		for (Map.Entry<Long, List<BusinessAssayTaskDataDO>> entry : businessAssayTaskDataByTaskMap.entrySet()) {
			Long businessAssayTaskId = entry.getKey();
			List<Long> currBusinessAssayTaskDataIdList = entry.getValue().stream().map(m -> m.getId()).collect(Collectors.toList());
			JSONObject json = sampleAnalysisAuditService.getCrossAuditDataByTaskId(businessAssayTaskId, currBusinessAssayTaskDataIdList);
			JSONObject businessAssayTaskJson = json.getJSONArray("businessAssayTask").getJSONObject(0);
			String configReportTemplateKey = businessAssayTaskJson.getString("configReportTemplateKey");
			String taskNo = businessAssayTaskJson.getString("taskNo");
			String taskName = businessAssayTaskJson.getString("taskName");
			String fileName = taskNo + "-" + taskName;
			String assayOperatorId = businessAssayTaskJson.getString("assayOperatorId");
			String assayOperator = businessAssayTaskJson.getString("assayOperator");
			assayOperatorIdSet.add(assayOperatorId);
			assayOperatorSet.add(assayOperator);
			
			ConfigReportTemplateDO gridppReportFile = configReportTemplateService.getConfigReportTemplateByKey(configReportTemplateKey);

	        //报表参数
	        Map<String, String> reportParams = new HashMap<>();
	        BinaryObject binaryObject;
			try {
				binaryObject = gridReport.genReport(gridppReportFile.getContent(), json.toJSONString(), reportParams, ExportType.PDF);
			} catch (Exception e) {
				throw new ServiceException(1_032_100_000, taskNo + "原始记录生成失败！");
			}
	        byte[] docBytes = PdfHelper.modifyDocInfo(binaryObject.getDataBuf());
	        //上传到文件服务
	        FileCreateReqDTO fileCreateReqDTO = new FileCreateReqDTO();
	        fileCreateReqDTO.setName(fileName);
	        fileCreateReqDTO.setDirectory(null);
	        fileCreateReqDTO.setType(null);
	        fileCreateReqDTO.setContent(docBytes);
	        CommonResult<FileRespDTO> fileResult = fileApi.createFileWithReturn(fileCreateReqDTO);
	        if (fileResult == null || !fileResult.isSuccess() || fileResult.getData() == null) {
	            throw new ServiceException(1_032_100_000, "通过文件服务创建附件失败: " + Optional.ofNullable(fileResult).map(CommonResult::getMsg).orElse("未知错误"));
	        }
	        FileRespDTO fileRespDTO = fileResult.getData();
	        //创建businessFile
	        BusinessFileSaveReqDTO businessFileSaveReqDTO = BusinessFileSaveReqDTO.builder()
	                .businessId(businessSampleEntrustDepartmentDO.getId())
	                .businessCode(taskNo)
	                .fileName(fileRespDTO.getName())
	                .fileId(fileRespDTO.getId())
	                .source(null)
	                .status(1)
	                .build();
	        businessFileApi.createBusinessFile(businessFileSaveReqDTO);

	        //设置附件
	        JSONObject fileExtInfoJSON = new JSONObject();
	        fileExtInfoJSON.put("taskNo", businessAssayTaskJson.getString("taskNo"));
	        fileExtInfoJSON.put("taskName", businessAssayTaskJson.getString("taskName"));
	        fileExtInfoJSON.put("assayOperator", businessAssayTaskJson.getString("assayOperator"));
	        fileExtInfoJSON.put("assayTime", businessAssayTaskJson.getString("assayTime"));
	        fileExtInfoJSON.put("reportOperator", businessAssayTaskJson.getString("reportOperator"));
	        fileExtInfoJSON.put("reportTime", businessAssayTaskJson.getString("reportTime"));
	        BusinessSampleEntrustFileDO businessSampleEntrustFileDO = new BusinessSampleEntrustFileDO();
	        businessSampleEntrustFileDO.setBusinessSampleEntrustRegistrationId(businessSampleEntrustDepartmentDO.getBusinessSampleEntrustRegistrationId());
	        businessSampleEntrustFileDO.setBusinessSampleEntrustDepartmentId(businessSampleEntrustDepartmentDO.getId());
	        businessSampleEntrustFileDO.setFileCategory(QmsCommonConstant.ENTRUST_ATTACHMENT_CATEGORY_ASSAY_TASK);
	        businessSampleEntrustFileDO.setFileId(fileRespDTO.getId());
	        businessSampleEntrustFileDO.setFileName(fileRespDTO.getName());
	        businessSampleEntrustFileDO.setFilePath(fileRespDTO.getDirectory());
	        businessSampleEntrustFileDO.setExternalInfomation(fileExtInfoJSON.toJSONString());
	        
	        businessSampleEntrustFileDOList.add(businessSampleEntrustFileDO);
			
		}
		businessSampleEntrustDepartmentDO.setAssayOperatorId(CollUtil.join(assayOperatorIdSet, ","));
		businessSampleEntrustDepartmentDO.setAssayOperator(CollUtil.join(assayOperatorSet, "、"));
		
		//检验委托
		List<BusinessSampleEntrustDepartmentDO> allBusinessSampleEntrustDepartmentDOList = businessSampleEntrustDepartmentMapper.selectByBusinessSampleEntrustRegistrationId(businessSampleEntrustDepartmentDO.getBusinessSampleEntrustRegistrationId());
		long count = allBusinessSampleEntrustDepartmentDOList.stream().filter(f -> !f.getId().equals(businessSampleEntrustDepartmentDO.getId()) && QmsCommonConstant.NO.equals(f.getIsReported())).count();//过滤除去当前分析部门外，其他未上报的分析部门数
		if (count <= 0) {//如果值为0，则说明都上报了，需要处理检验委托
			businessSampleEntrustRegistrationDO.setAssayStatus(QmsCommonConstant.CHECKED);
			businessSampleEntrustRegistrationMapper.updateById(businessSampleEntrustRegistrationDO);
			
			//TODO 新增个配置是否发送到消息队列
			if (true) {
				SampleEntrustRegistrationAssayCompleteMessage message = new SampleEntrustRegistrationAssayCompleteMessage();
				message.setBusinessSampleEntrustRegistrationId(businessSampleEntrustRegistrationDO.getId())
					   .setConfigEntrustSourceId(businessSampleEntrustRegistrationDO.getConfigEntrustSourceId())
					   .setEntrustNumber(businessSampleEntrustRegistrationDO.getEntrustNumber())
					   .setEntrustUnit(businessSampleEntrustRegistrationDO.getEntrustUnit());
				sampleEntrustRegistrationAssayCompleteProducer.sendMessage(message);
			}
		}
		
		//生成部门报告pdf
		//查询报表数据
		List<BusinessAssayReportDataExtendRespVO> businessAssayReportDataList = businessAssayReportDataMapper.selectExtendByBusinessBaseSampleIds(businessBaseSampleIdList);
		com.alibaba.fastjson.JSONObject jsonObjectParam = new com.alibaba.fastjson.JSONObject();
		com.alibaba.fastjson.JSONObject signatureData = new com.alibaba.fastjson.JSONObject();
		signatureData.put("Activity_002", new HashMap<String, Object>(){
			private static final long serialVersionUID = -1530865046649241282L;
			{
				put("userName", businessSampleEntrustDepartmentDO.getReportOperator());
				put("signTime", DateUtil.formatLocalDateTime(businessSampleEntrustDepartmentDO.getReportTime()));
			}
		});
		com.alibaba.fastjson.JSONObject formData = new com.alibaba.fastjson.JSONObject();
		formData.put("assayOperator", businessSampleEntrustDepartmentDO.getAssayOperator());
		formData.put("sampleCategory", sampleCategory);
		formData.put("entrustCode", businessSampleEntrustRegistrationDO.getEntrustNumber());
		
		jsonObjectParam.put("assayReportDataList", JSON.parseArray(JSON.toJSONString(businessAssayReportDataList)));
		jsonObjectParam.put("itemNameList", param.getAssayProject());
		jsonObjectParam.put("signatureData", signatureData);
		jsonObjectParam.put("formData", formData);
		CommonResult<JSONArray> assembleByReportData = reportDocumentDataService.assembleByReportData(jsonObjectParam);
		byte[] reportPDF = null;
		try {
			byte[] docBytes = reportDocumentAssistService.generateReportPDF(assembleByReportData.getData(), businessSampleEntrustDepartmentDO.getDataTemplateId());
			reportPDF = PdfHelper.modifyDocInfo(docBytes, businessSampleEntrustRegistrationDO.getEntrustNumber() + "-" + businessSampleEntrustDepartmentDO.getAssayDepartmentName(), null, null, null, null, null);
		} catch (IOException e) {
			throw new ServiceException(1_032_100_000, businessSampleEntrustRegistrationDO.getEntrustNumber() + "-" + businessSampleEntrustDepartmentDO.getAssayDepartmentName() + "商检报告生成失败！");
		}
		//上传到文件服务
        FileCreateReqDTO fileCreateReqDTO = new FileCreateReqDTO();
        fileCreateReqDTO.setName(businessSampleEntrustRegistrationDO.getEntrustNumber() + "-" + businessSampleEntrustDepartmentDO.getAssayDepartmentName()+".pdf");
        fileCreateReqDTO.setDirectory(null);
        fileCreateReqDTO.setType(null);
        fileCreateReqDTO.setContent(reportPDF);
        CommonResult<FileRespDTO> fileResult = fileApi.createFileWithReturn(fileCreateReqDTO);
        if (fileResult == null || !fileResult.isSuccess() || fileResult.getData() == null) {
            throw new ServiceException(1_032_100_000, "通过文件服务创建附件失败: " + Optional.ofNullable(fileResult).map(CommonResult::getMsg).orElse("未知错误"));
        }
        FileRespDTO fileRespDTO = fileResult.getData();
        //创建businessFile
        BusinessFileSaveReqDTO businessFileSaveReqDTO = BusinessFileSaveReqDTO.builder()
                .businessId(businessSampleEntrustDepartmentDO.getId())
                .businessCode(businessSampleEntrustRegistrationDO.getEntrustNumber())
                .fileName(fileRespDTO.getName())
                .fileId(fileRespDTO.getId())
                .source(null)
                .status(1)
                .build();
        businessFileApi.createBusinessFile(businessFileSaveReqDTO);

        //设置附件
        JSONObject fileExtInfoJSON = new JSONObject();
        fileExtInfoJSON.put("entrustNumber", businessSampleEntrustRegistrationDO.getEntrustNumber());
        fileExtInfoJSON.put("assayDepartmentName", businessSampleEntrustDepartmentDO.getAssayDepartmentName());
        fileExtInfoJSON.put("reportOperator", businessSampleEntrustDepartmentDO.getReportOperator());
        fileExtInfoJSON.put("reportTime", DateUtil.formatLocalDateTime(businessSampleEntrustDepartmentDO.getReportTime()));
        BusinessSampleEntrustFileDO businessSampleEntrustFileDO = new BusinessSampleEntrustFileDO();
        businessSampleEntrustFileDO.setBusinessSampleEntrustRegistrationId(businessSampleEntrustDepartmentDO.getBusinessSampleEntrustRegistrationId());
        businessSampleEntrustFileDO.setBusinessSampleEntrustDepartmentId(businessSampleEntrustDepartmentDO.getId());
        businessSampleEntrustFileDO.setFileCategory(QmsCommonConstant.ENTRUST_ATTACHMENT_CATEGORY_DEPT_DOC);
        businessSampleEntrustFileDO.setFileId(fileRespDTO.getId());
        businessSampleEntrustFileDO.setFileName(fileRespDTO.getName());
        businessSampleEntrustFileDO.setFilePath(fileRespDTO.getDirectory());
        businessSampleEntrustFileDO.setExternalInfomation(fileExtInfoJSON.toJSONString());
        
        businessSampleEntrustFileDOList.add(businessSampleEntrustFileDO);
		
		//更新委检登记部门分析信息
		businessSampleEntrustDepartmentMapper.updateById(businessSampleEntrustDepartmentDO);
		
		//保存原始记录附件信息
		if (CollUtil.isNotEmpty(businessSampleEntrustFileDOList)) {
			businessSampleEntrustFileMapper.insertBatch(businessSampleEntrustFileDOList);
		}
		
	}

}
