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

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yomahub.liteflow.flow.LiteflowResponse;
import com.zt.plat.module.qms.business.bus.liteflow.param.SampleEntrustDetail;
import com.zt.plat.module.qms.business.bus.liteflow.param.SampleEntrustDetailProject;
import com.zt.plat.module.qms.business.bus.liteflow.param.SampleEntrustParam;
import com.zt.plat.module.qms.business.bus.liteflow.slot.SampleEntrustContext;
import com.zt.plat.module.qms.business.bus.service.SampleEntrustService;
import com.zt.plat.module.qms.business.config.controller.vo.MaterialAssayStandardDetailRespVO;
import com.zt.plat.module.qms.business.config.dal.mapper.MaterialAssayStandardDetailMapper;
import com.zt.plat.module.qms.business.other.controller.vo.OtherDictionaryProjectExtendRespVO;
import com.zt.plat.module.qms.business.other.dal.dataobject.OtherBaseSampleDO;
import com.zt.plat.module.qms.business.other.dal.dataobject.OtherDictionaryBusinessDO;
import com.zt.plat.module.qms.business.other.dal.dataobject.OtherDictionaryProjectDO;
import com.zt.plat.module.qms.business.other.dal.dataobject.OtherSystemUserDO;
import com.zt.plat.module.qms.business.other.dal.mapper.OtherBaseSampleMapper;
import com.zt.plat.module.qms.business.other.dal.mapper.OtherDictionaryBusinessMapper;
import com.zt.plat.module.qms.business.other.dal.mapper.OtherDictionaryProjectMapper;
import com.zt.plat.module.qms.business.other.dal.mapper.OtherSystemUserMapper;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.qms.thirdpartyapi.controller.vo.ThirdpartyXntSampleEntrustReqVO;

import jakarta.annotation.Resource;

/**
 * 西南铜委托创建服务
 */
@Service
public class ThirdpartyXntSampleEntrustServiceImpl implements ThirdpartyXntSampleEntrustService {

	@Resource
	private SampleEntrustService sampleEntrustService;
	
	@Resource
	private OtherBaseSampleMapper otherBaseSampleMapper;
	
	@Resource
	private OtherSystemUserMapper otherSystemUserMapper;
	
	@Resource
	private OtherDictionaryProjectMapper otherDictionaryProjectMapper;
	
	@Resource
	private OtherDictionaryBusinessMapper otherDictionaryBusinessMapper;
	
	@Resource
	private MaterialAssayStandardDetailMapper materialAssayStandardDetailMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createRawMaterial(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		SampleEntrustParam sampleEntrustParam = buildSampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_RAW_MATERIAL);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createSupplier(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		SampleEntrustParam sampleEntrustParam = buildSampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_SUPPLIER);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createProduct(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		SampleEntrustParam sampleEntrustParam = buildSampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_PRODUCT);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createInProcessControl(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		SampleEntrustParam sampleEntrustParam = buildSampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_IN_PROCESS_CONTROL);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createReTest(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		SampleEntrustParam sampleEntrustParam = buildSampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_RETEST);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createProductReTest(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		SampleEntrustParam sampleEntrustParam = buildSampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_PRODUCT_RETEST);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createCentralRetentionReTest(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		SampleEntrustParam sampleEntrustParam = buildSampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_CENTRAL_RETENTIN_RETEST);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createTemporary(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList) {
		//构建临时样委托参数
		SampleEntrustParam sampleEntrustParam = buildTemporarySampleEntrustParam(sampleEntrustReqVOList, QmsCommonConstant.ENTRUST_SOURCE_XNT_TEMPORARY);
		LiteflowResponse liteflowResponse = sampleEntrustService.create(sampleEntrustParam);
		SampleEntrustContext sampleEntrustContext = liteflowResponse.getContextBean(SampleEntrustContext.class);
		
	}
	
	private SampleEntrustParam buildTemporarySampleEntrustParam(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList, String configEntrustSourceKey) {
		SampleEntrustParam sampleEntrustParam = new SampleEntrustParam();
		sampleEntrustParam.setCreateWay("interface");
		sampleEntrustParam.setEntrustTime(LocalDateTime.now());
		sampleEntrustParam.setEntrustType(QmsCommonConstant.ENTRUST_REGISTRATION);
		sampleEntrustParam.setConfigEntrustSourceKey(configEntrustSourceKey);
		sampleEntrustParam.setEntrustUnit("西南铜");
		sampleEntrustParam.setSampleQuantity(sampleEntrustReqVOList.size());
		
		sampleEntrustParam.setSampleSendDate(LocalDateTime.now());
		
		List<String> limsObjectIdList = sampleEntrustReqVOList.stream().map(m -> m.getLimsObjectId()).distinct().collect(Collectors.toList());
		List<OtherBaseSampleDO> otherBaseSampleDOList = otherBaseSampleMapper.selectByOtherSystemAndOtherIds(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS, limsObjectIdList);
//		List<Long> baseSampleIdList = otherBaseSampleDOList.stream().map(m -> m.getBaseSampleId()).distinct().collect(Collectors.toList());
//		List<MaterialAssayStandardDetailRespVO> materialAssayStandardDetailRespList = materialAssayStandardDetailMapper.selectByBaseSampleIds(baseSampleIdList);
		//获取第三方送样人id列表
		List<String> otherSendUserIdList = sampleEntrustReqVOList.stream().flatMap(m -> {
			// 按逗号分割
            String[] parts = m.getEntrustSampleSenderIds().split(",");
            
            // 转为 Stream 并处理空格 (trim)，同时过滤掉分割后可能产生的空字符串
            return Arrays.stream(parts)
                .map(String::trim)          // 去除每个ID前后的空格
                .filter(s -> !s.isEmpty()); // 过滤掉空项（例如 "101,,102" 中间的空项）
		}).distinct().collect(Collectors.toList());
		
		List<OtherSystemUserDO> otherSystemUserDOList = otherSystemUserMapper.selectByOtherSystemAndOtherIds(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS, otherSendUserIdList);
		
		List<OtherDictionaryBusinessDO> otherDictionaryBusinessDOList = otherDictionaryBusinessMapper.selectByOtherSystem(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS);
		
		List<SampleEntrustDetail> sampleEntrustDetailList = new ArrayList<>();
		for (ThirdpartyXntSampleEntrustReqVO thirdpartySampleEntrustReqVO : sampleEntrustReqVOList) {
			OtherBaseSampleDO otherBaseSampleDO = otherBaseSampleDOList.stream().filter(f -> f.getOtherId().equals(thirdpartySampleEntrustReqVO.getLimsObjectId())).findFirst().orElse(null);
			
			SampleEntrustDetail sampleEntrustDetail = new SampleEntrustDetail();
			sampleEntrustDetail.setBaseSampleId(otherBaseSampleDO.getBaseSampleId());
			sampleEntrustDetail.setEntrustGroupCode(thirdpartySampleEntrustReqVO.getEntrustGroupCode());
			sampleEntrustDetail.setEntrustBatchCode(thirdpartySampleEntrustReqVO.getEntrustBatchCode());
			sampleEntrustDetail.setEntrustDualFlag(null);
			sampleEntrustDetail.setEntrustSampleName(thirdpartySampleEntrustReqVO.getLimsObjectName());
			sampleEntrustDetail.setEntrustSampleCode(thirdpartySampleEntrustReqVO.getEntrustSampleCode());
			sampleEntrustDetail.setSampleName(thirdpartySampleEntrustReqVO.getLimsObjectName());
			sampleEntrustDetail.setSampleCode(thirdpartySampleEntrustReqVO.getEntrustSampleCode());
			if (StringUtils.isNotBlank(thirdpartySampleEntrustReqVO.getEntrustSampleQuantity())) {
				sampleEntrustDetail.setIsWeighing(QmsCommonConstant.YES);
			} else {
				sampleEntrustDetail.setIsWeighing(QmsCommonConstant.NO);
			}
			sampleEntrustDetail.setEntrustSampleQuantity(thirdpartySampleEntrustReqVO.getEntrustSampleQuantity());
			sampleEntrustDetail.setEntrustSampleQuantityUnit(thirdpartySampleEntrustReqVO.getEntrustSampleQuantityUnit());
			
			//处理分析等级
			if (StringUtils.isNotBlank(thirdpartySampleEntrustReqVO.getAssayLevel())) {
				OtherDictionaryBusinessDO otherDictionaryBusinessDO = otherDictionaryBusinessDOList.stream().filter(f -> f.getOtherKey().equals(thirdpartySampleEntrustReqVO.getAssayLevel())).findFirst().orElse(null);
				sampleEntrustDetail.setAssayLevel(Integer.parseInt(otherDictionaryBusinessDO.getDictionaryBusinessKey()));
			}
			
			String entrustSampleSenderIds = thirdpartySampleEntrustReqVO.getEntrustSampleSenderIds();
			String sampleSender = otherSystemUserDOList.stream().filter(f -> Arrays.asList(entrustSampleSenderIds.split(",")).contains(f.getOtherId())).map(m -> m.getUserRealName()).collect(Collectors.joining(","));
			sampleEntrustParam.setSampleSender(sampleSender);
			
			String assayProjectIds = thirdpartySampleEntrustReqVO.getAssayProjectIds();
			List<String> assayProjectIdList = Arrays.asList(assayProjectIds.split(","));
			List<OtherDictionaryProjectExtendRespVO> otherDictionaryProjectDOList = otherDictionaryProjectMapper.selectExtendByOtherSystemAndOtherIds(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS, assayProjectIdList);
//			List<Long> dictionaryProjectIdList = otherDictionaryProjectDOList.stream().map(m -> m.getDictionaryProjectId()).collect(Collectors.toList());
//			List<MaterialAssayStandardDetailRespVO> currMaterialAssayStandardDetailList = materialAssayStandardDetailRespList.stream().filter(f -> f.getBaseSampleId().equals(otherBaseSampleDO.getBaseSampleId()) && dictionaryProjectIdList.contains(f.getDictionaryProjectId())).collect(Collectors.toList());
//			String assayProjectShowName = currMaterialAssayStandardDetailList.stream().map(m -> m.getDictionaryProjectShowName()).collect(Collectors.joining(","));
			String assayProjectShowName = otherDictionaryProjectDOList.stream().map(m -> m.getDictionaryProjectShowName()).collect(Collectors.joining(","));
			sampleEntrustDetail.setAssayProject(assayProjectShowName);
			List<SampleEntrustDetailProject> sampleEntrustDetailProjectList = new ArrayList<>();
			for (OtherDictionaryProjectExtendRespVO otherDictionaryProject : otherDictionaryProjectDOList) {
				SampleEntrustDetailProject sampleEntrustDetailProject = new SampleEntrustDetailProject();
				sampleEntrustDetailProject.setDictionaryProjectId(otherDictionaryProject.getDictionaryProjectId());
				sampleEntrustDetailProject.setIsEnabled(QmsCommonConstant.YES);
				sampleEntrustDetailProjectList.add(sampleEntrustDetailProject);
			}
			sampleEntrustDetail.setSampleEntrustDetailProjectList(sampleEntrustDetailProjectList);
			
			sampleEntrustDetailList.add(sampleEntrustDetail);
		}
		
		
		sampleEntrustParam.setSampleEntrustDetailList(sampleEntrustDetailList);
		
		
		return sampleEntrustParam;
	}

	private SampleEntrustParam buildSampleEntrustParam(List<ThirdpartyXntSampleEntrustReqVO> sampleEntrustReqVOList, String configEntrustSourceKey) {
		SampleEntrustParam sampleEntrustParam = new SampleEntrustParam();
		sampleEntrustParam.setCreateWay("interface");
		sampleEntrustParam.setEntrustTime(LocalDateTime.now());
		sampleEntrustParam.setEntrustType(QmsCommonConstant.ENTRUST_REGISTRATION);
		sampleEntrustParam.setConfigEntrustSourceKey(configEntrustSourceKey);
		sampleEntrustParam.setEntrustUnit("西南铜");
		sampleEntrustParam.setSampleQuantity(sampleEntrustReqVOList.size());
		
		sampleEntrustParam.setSampleSendDate(LocalDateTime.now());
		
		List<String> limsObjectIdList = sampleEntrustReqVOList.stream().map(m -> m.getLimsObjectId()).distinct().collect(Collectors.toList());
		List<OtherBaseSampleDO> otherBaseSampleDOList = otherBaseSampleMapper.selectByOtherSystemAndOtherIds(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS, limsObjectIdList);
		List<Long> baseSampleIdList = otherBaseSampleDOList.stream().map(m -> m.getBaseSampleId()).distinct().collect(Collectors.toList());
		List<MaterialAssayStandardDetailRespVO> materialAssayStandardDetailRespList = materialAssayStandardDetailMapper.selectByBaseSampleIds(baseSampleIdList);
		//获取第三方送样人id列表
		List<String> otherSendUserIdList = sampleEntrustReqVOList.stream().flatMap(m -> {
			// 按逗号分割
            String[] parts = m.getEntrustSampleSenderIds().split(",");
            
            // 转为 Stream 并处理空格 (trim)，同时过滤掉分割后可能产生的空字符串
            return Arrays.stream(parts)
                .map(String::trim)          // 去除每个ID前后的空格
                .filter(s -> !s.isEmpty()); // 过滤掉空项（例如 "101,,102" 中间的空项）
		}).distinct().collect(Collectors.toList());
		
		List<OtherSystemUserDO> otherSystemUserDOList = otherSystemUserMapper.selectByOtherSystemAndOtherIds(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS, otherSendUserIdList);
		
		List<OtherDictionaryBusinessDO> otherDictionaryBusinessDOList = otherDictionaryBusinessMapper.selectByOtherSystem(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS);
		
		List<SampleEntrustDetail> sampleEntrustDetailList = new ArrayList<>();
		for (ThirdpartyXntSampleEntrustReqVO thirdpartySampleEntrustReqVO : sampleEntrustReqVOList) {
			OtherBaseSampleDO otherBaseSampleDO = otherBaseSampleDOList.stream().filter(f -> f.getOtherId().equals(thirdpartySampleEntrustReqVO.getLimsObjectId())).findFirst().orElse(null);
			
			SampleEntrustDetail sampleEntrustDetail = new SampleEntrustDetail();
			sampleEntrustDetail.setBaseSampleId(otherBaseSampleDO.getBaseSampleId());
			sampleEntrustDetail.setEntrustGroupCode(thirdpartySampleEntrustReqVO.getEntrustGroupCode());
			sampleEntrustDetail.setEntrustBatchCode(thirdpartySampleEntrustReqVO.getEntrustBatchCode());
			sampleEntrustDetail.setEntrustDualFlag(null);
			sampleEntrustDetail.setEntrustSampleName(thirdpartySampleEntrustReqVO.getLimsObjectName());
			sampleEntrustDetail.setEntrustSampleCode(thirdpartySampleEntrustReqVO.getEntrustSampleCode());
			sampleEntrustDetail.setSampleName(thirdpartySampleEntrustReqVO.getLimsObjectName());
			sampleEntrustDetail.setSampleCode(thirdpartySampleEntrustReqVO.getEntrustSampleCode());
			if (StringUtils.isNotBlank(thirdpartySampleEntrustReqVO.getEntrustSampleQuantity())) {
				sampleEntrustDetail.setIsWeighing(QmsCommonConstant.YES);
			} else {
				sampleEntrustDetail.setIsWeighing(QmsCommonConstant.NO);
			}
			sampleEntrustDetail.setEntrustSampleQuantity(thirdpartySampleEntrustReqVO.getEntrustSampleQuantity());
			sampleEntrustDetail.setEntrustSampleQuantityUnit(thirdpartySampleEntrustReqVO.getEntrustSampleQuantityUnit());
			
			//处理分析等级
			if (StringUtils.isNotBlank(thirdpartySampleEntrustReqVO.getAssayLevel())) {
				OtherDictionaryBusinessDO otherDictionaryBusinessDO = otherDictionaryBusinessDOList.stream().filter(f -> f.getOtherKey().equals(thirdpartySampleEntrustReqVO.getAssayLevel())).findFirst().orElse(null);
				sampleEntrustDetail.setAssayLevel(Integer.parseInt(otherDictionaryBusinessDO.getDictionaryBusinessKey()));
			}
			
			String entrustSampleSenderIds = thirdpartySampleEntrustReqVO.getEntrustSampleSenderIds();
			String sampleSender = otherSystemUserDOList.stream().filter(f -> Arrays.asList(entrustSampleSenderIds.split(",")).contains(f.getOtherId())).map(m -> m.getUserRealName()).collect(Collectors.joining(","));
			sampleEntrustParam.setSampleSender(sampleSender);
			
			String assayProjectIds = thirdpartySampleEntrustReqVO.getAssayProjectIds();
			List<String> assayProjectIdList = Arrays.asList(assayProjectIds.split(","));
			List<OtherDictionaryProjectDO> otherDictionaryProjectDOList = otherDictionaryProjectMapper.selectByOtherSystemAndOtherIds(QmsCommonConstant.OTHER_SYSTEM_XNT_LIMS, assayProjectIdList);
			List<Long> dictionaryProjectIdList = otherDictionaryProjectDOList.stream().map(m -> m.getDictionaryProjectId()).collect(Collectors.toList());
			List<MaterialAssayStandardDetailRespVO> currMaterialAssayStandardDetailList = materialAssayStandardDetailRespList.stream().filter(f -> f.getBaseSampleId().equals(otherBaseSampleDO.getBaseSampleId()) && dictionaryProjectIdList.contains(f.getDictionaryProjectId())).collect(Collectors.toList());
			String assayProjectShowName = currMaterialAssayStandardDetailList.stream().map(m -> m.getDictionaryProjectShowName()).collect(Collectors.joining(","));
			sampleEntrustDetail.setAssayProject(assayProjectShowName);
			List<SampleEntrustDetailProject> sampleEntrustDetailProjectList = new ArrayList<>();
			for (MaterialAssayStandardDetailRespVO currMaterialAssayStandardDetail : currMaterialAssayStandardDetailList) {
				SampleEntrustDetailProject sampleEntrustDetailProject = new SampleEntrustDetailProject();
				sampleEntrustDetailProject.setMaterialAssayStandardDetailId(currMaterialAssayStandardDetail.getId());
				sampleEntrustDetailProject.setIsEnabled(QmsCommonConstant.YES);
				sampleEntrustDetailProjectList.add(sampleEntrustDetailProject);
			}
			sampleEntrustDetail.setSampleEntrustDetailProjectList(sampleEntrustDetailProjectList);
			
			sampleEntrustDetailList.add(sampleEntrustDetail);
		}
		
		
		sampleEntrustParam.setSampleEntrustDetailList(sampleEntrustDetailList);
		
		
		return sampleEntrustParam;
	}
}
