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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.qms.business.bus.controller.vo.*;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessAssayTaskDataDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessHandoverRecordSubDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleHandoverDetailDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleAnalysisGroupDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigSubSampleDO;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigWarehouseLocationDO;
import com.zt.plat.module.qms.business.config.service.ConfigSubSampleService;
import com.zt.plat.module.qms.business.config.service.ConfigWarehouseLocationService;
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.common.dic.service.DictionaryBusinessService;
import com.zt.plat.module.qms.core.code.SequenceUtil;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.qms.enums.QmsWarehouseLocationConstant;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
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.BusinessSubSampleAnalysisGroupMapper;
import com.zt.plat.module.qms.business.bus.dal.mapper.BusinessSubSampleMapper;
import com.zt.plat.module.qms.enums.QmsCommonConstant;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception0;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;
import static com.zt.plat.module.qms.enums.QmsCommonConstant.SAMPLE_STORAGE_OPERATION_TYPE_TAKEN_OFF;

/**
 * 子样业务 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class BusinessSubSampleServiceImpl implements BusinessSubSampleService {

    @Resource
    private BusinessSubSampleMapper businessSubSampleMapper;
    
    @Resource
    private BusinessSubSampleAnalysisGroupMapper businessSubSampleAnalysisGroupMapper;
    
    @Resource
    private BusinessAssayTaskDataMapper businessAssayTaskDataMapper;

    @Resource private ConfigWarehouseLocationService configWarehouseLocationService;
    @Resource private BusinessSampleHandoverService businessSampleHandoverService;
    @Resource private BusinessSampleHandoverDetailService businessSampleHandoverDetailService;
    @Resource private BusinessHandoverRecordSubService businessHandoverRecordSubService;
    @Resource private DictionaryBusinessService dictionaryBusinessService;
    @Resource private ConfigSubSampleService configSubSampleService;
    @Resource private SequenceUtil sequenceUtil;
    @Resource
    private DictionaryBusinessMapper dictionaryBusinessMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(List<BusinessSubSampleDO> businessSubSampleDOList) {
        businessSubSampleMapper.updateBatch(businessSubSampleDOList);
    }

    @Override
    public List<BusinessSubSampleDO> listByIdList(List<Long> idList) {
        return businessSubSampleMapper.selectByIds(idList);
    }

    @Override
    public BusinessSubSampleRespVO createBusinessSubSample(BusinessSubSampleSaveReqVO createReqVO) {
        // 插入
        BusinessSubSampleDO businessSubSample = BeanUtils.toBean(createReqVO, BusinessSubSampleDO.class);
        businessSubSampleMapper.insert(businessSubSample);
        // 返回
        return BeanUtils.toBean(businessSubSample, BusinessSubSampleRespVO.class);
    }

    @Override
    public void updateBusinessSubSample(BusinessSubSampleSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessSubSampleExists(updateReqVO.getId());
        // 更新
        BusinessSubSampleDO updateObj = BeanUtils.toBean(updateReqVO, BusinessSubSampleDO.class);
        businessSubSampleMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessSubSample(Long id) {
        // 校验存在
        validateBusinessSubSampleExists(id);
        // 删除
        businessSubSampleMapper.deleteById(id);
    }

    @Override
        public void deleteBusinessSubSampleListByIds(List<Long> ids) {
        // 校验存在
        validateBusinessSubSampleExists(ids);
        // 删除
        businessSubSampleMapper.deleteByIds(ids);
        }

    private void validateBusinessSubSampleExists(List<Long> ids) {
        List<BusinessSubSampleDO> list = businessSubSampleMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BUSINESS_SUB_SAMPLE_NOT_EXISTS);
        }
    }

    private void validateBusinessSubSampleExists(Long id) {
        if (businessSubSampleMapper.selectById(id) == null) {
            throw exception(BUSINESS_SUB_SAMPLE_NOT_EXISTS);
        }
    }

    @Override
    public BusinessSubSampleExtendRespVO getBusinessSubSample(Long id) {
        return businessSubSampleMapper.selectExtendById(id);
    }

	@Override
	public BusinessSubSampleExtendRespVO getPrintSubSample(Long id) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
    	BusinessSubSampleExtendRespVO businessSubSample = businessSubSampleMapper.selectExtendById(id);
    	BusinessSubSampleAnalysisGroupDO businessSubSampleAnalysisGroupDO = businessSubSampleAnalysisGroupMapper.selectByBusinessSubSampleIdAndAssayDepartmentId(id, loginUser.getVisitDeptId());
    	businessSubSample.setAssayDepartmentId(businessSubSampleAnalysisGroupDO.getAssayDepartmentId());
    	businessSubSample.setAssayDepartmentName(businessSubSampleAnalysisGroupDO.getAssayDepartmentName());
    	businessSubSample.setSampleReceiver(businessSubSampleAnalysisGroupDO.getSampleReceiver());
    	businessSubSample.setSampleReceiveTime(businessSubSampleAnalysisGroupDO.getSampleReceiveTime());
    	List<BusinessAssayTaskDataDO> businessAssayTaskDataDOList = businessAssayTaskDataMapper.selectByBusinessSubSampleIdAndAssayDepartmentId(id, loginUser.getVisitDeptId());
    	List<String> assayProjectList = new ArrayList<>();
    	for (BusinessAssayTaskDataDO businessAssayTaskDataDO : businessAssayTaskDataDOList) {
			String assayProject = businessAssayTaskDataDO.getAssayProject();
			String[] split = assayProject.split(",");
			for (String s : split) {
				if (!assayProjectList.contains(s)) {
					assayProjectList.add(s);
				}
			}
		}
    	businessSubSample.setAssayProject(CollUtil.join(assayProjectList, ","));
		return businessSubSample;
	}

    @Override
    public BusinessSubSampleDO getBySampleCode(String sampleCode) {
        LambdaQueryWrapper<BusinessSubSampleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessSubSampleDO::getSampleCode, sampleCode);
        return businessSubSampleMapper.selectOne(queryWrapper);
    }

    @Override
    public BusinessSubSampleDO getBySampleReturnCode(String sampleReturnCode) {
        LambdaQueryWrapper<BusinessSubSampleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessSubSampleDO::getSampleReturnCode, sampleReturnCode);
        return businessSubSampleMapper.selectOne(queryWrapper);
    }

    @Override
    public PageResult<BusinessSubSampleExtendRespVO> getBusinessSubSamplePage(BusinessSubSamplePageReqVO pageReqVO) {
    	PageResult<BusinessSubSampleExtendRespVO> page = businessSubSampleMapper.selectPage(pageReqVO);
    	List<BusinessSubSampleExtendRespVO> list = page.getList();
    	if (CollUtil.isNotEmpty(list)) {
        	List<Long> subSampleIdList = list.stream().map(m -> m.getId()).collect(Collectors.toList());
        	List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupList = businessSubSampleAnalysisGroupMapper.selectByBusinessSubSampleIds(subSampleIdList);

        	for (BusinessSubSampleExtendRespVO businessSubSampleExtendRespVO : list) {
        		List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupDOList = businessSubSampleAnalysisGroupList.stream().filter(f -> f.getBusinessSubSampleId().equals(businessSubSampleExtendRespVO.getId())).collect(Collectors.toList());
        		businessSubSampleExtendRespVO.setBusinessSubSampleAnalysisGroupList(BeanUtils.toBean(businessSubSampleAnalysisGroupDOList, BusinessSubSampleAnalysisGroupRespVO.class));
    		}
		}
        return page;
    }

    @Override
    public PageResult<BusinessSubSampleExtendRespVO> selectPageForDispatch(BusinessSubSamplePageReqVO pageReqVO) {
        IPage<BusinessSubSampleExtendRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        Page<BusinessSubSampleExtendRespVO> pageList = businessSubSampleMapper.selectPageForDispatch(page, pageReqVO);
        PageResult<BusinessSubSampleExtendRespVO> ret = new PageResult<>(pageList.getRecords(), pageList.getTotal());
        return ret;
    }

    @Override
	public PageResult<BusinessSubSampleExtendRespVO> getAnalysisGroupPage(BusinessSubSamplePageReqVO pageReqVO) {
		PageResult<BusinessSubSampleExtendRespVO> page = businessSubSampleMapper.selectAnalysisGroupPage(pageReqVO);
    	List<BusinessSubSampleExtendRespVO> list = page.getList();
    	if (CollUtil.isNotEmpty(list)) {
        	List<Long> subSampleIdList = list.stream().map(m -> m.getId()).collect(Collectors.toList());
        	List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupList = businessSubSampleAnalysisGroupMapper.selectByBusinessSubSampleIds(subSampleIdList);

        	for (BusinessSubSampleExtendRespVO businessSubSampleExtendRespVO : list) {
        		List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupDOList = businessSubSampleAnalysisGroupList.stream().filter(f -> f.getBusinessSubSampleId().equals(businessSubSampleExtendRespVO.getId())).collect(Collectors.toList());
        		businessSubSampleExtendRespVO.setBusinessSubSampleAnalysisGroupList(BeanUtils.toBean(businessSubSampleAnalysisGroupDOList, BusinessSubSampleAnalysisGroupRespVO.class));
    		}
		}
        return page;
	}

	@Override
	public List<BusinessSubSampleExtendRespVO> getBusinessSubSampleList(BusinessSubSampleReqVO reqVO) {
		List<BusinessSubSampleExtendRespVO> list = businessSubSampleMapper.selectList(reqVO);
		if (CollUtil.isNotEmpty(list)) {
        	List<Long> subSampleIdList = list.stream().map(m -> m.getId()).collect(Collectors.toList());
        	List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupList = businessSubSampleAnalysisGroupMapper.selectByBusinessSubSampleIds(subSampleIdList);

        	for (BusinessSubSampleExtendRespVO businessSubSampleExtendRespVO : list) {
        		List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupDOList = businessSubSampleAnalysisGroupList.stream().filter(f -> f.getBusinessSubSampleId().equals(businessSubSampleExtendRespVO.getId())).collect(Collectors.toList());
        		businessSubSampleExtendRespVO.setBusinessSubSampleAnalysisGroupList(BeanUtils.toBean(businessSubSampleAnalysisGroupDOList, BusinessSubSampleAnalysisGroupRespVO.class));
    		}
		}
		return list;
	}

	@Override
	public List<BusinessSubSampleExtendRespVO> getBySampleCodeAndFlowKey(@Valid BusinessSubSampleReqVO reqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        
        List<BusinessSubSampleExtendRespVO>  subSampleList = new ArrayList<>();
		if (QmsCommonConstant.FLOW_NODE_TEAM_RECEIVE.equals(reqVO.getSampleFlowNodeKey())) {
//			List<BusinessSubSampleExtendRespVO> sampleList = businessSubSampleMapper.getBySampleCode(reqVO);
			List<BusinessSubSampleExtendRespVO> sampleList = businessSubSampleMapper.getBySampleCodeAndFlowKey(reqVO);
			if (sampleList == null  || sampleList.size() <= 0) {
				return subSampleList;
			}
			for (BusinessSubSampleExtendRespVO sample : sampleList) {
				List<BusinessSubSampleAnalysisGroupDO> businessSubSampleAnalysisGroupList = businessSubSampleAnalysisGroupMapper.selectByBusinessSubSampleId(sample.getId());
				BusinessSubSampleAnalysisGroupDO receiveSample = businessSubSampleAnalysisGroupList.stream().filter(f -> "待收样".equals(f.getSampleStatus()) && f.getAssayDepartmentId().equals(loginUser.getVisitDeptId())).findFirst().orElse(null);
				if (receiveSample != null) {
					subSampleList.add(sample);
//					throw new ServiceException(1_032_100_000, "当前样品不在" + loginUser.getVisitDeptName() + "，不允许收样！");
				}
			}
		} else {
			subSampleList = businessSubSampleMapper.getBySampleCodeAndFlowKey(reqVO);
		}
		return subSampleList;
	}

    //样品归库
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusinessSubSampleRespVO execReturnToStock(BusinessSubSampleSaveReqVO reqVo) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        String loginUserName = SecurityFrameworkUtils.getLoginUserNickname();
        BusinessSubSampleDO businessSubSampleDO = this.getBySampleReturnCode(reqVo.getSampleReturnCode());
        if(businessSubSampleDO == null)
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "未查询到子样数据，请检查：样品所处环节和是否已归库！");
        //检查样品状态
        if(!QmsCommonConstant.FLOW_SAMPLE_STORAGE.equals(businessSubSampleDO.getSampleFlowNodeKey()))
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "子样任务不在“归库”环节，请检查前置任务是否已完成！");
        if(QmsCommonConstant.COMPLETED.equals(businessSubSampleDO.getReturnStatus()))
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "样品已归库，请勿重复操作！");

        //判断仓库位置
        Long configSubSampleId = businessSubSampleDO.getConfigSubSampleId();
        ConfigSubSampleDO configSubSampleDO = configSubSampleService.getConfigSubSample(configSubSampleId);
        String cfgLocationCode = configSubSampleDO.getConfigWarehouseLocationCode();    //子样配置表的仓库编码
        ConfigWarehouseLocationDO locationDO = configWarehouseLocationService.getLocationByCode(reqVo.getWarehouseLocationCode(), QmsWarehouseLocationConstant.WAREHOUSE_TYPE_SAMPLE);
        if(locationDO == null)
            throw exception(CONFIG_WAREHOUSE_LOCATION_NOT_EXISTS);
        ConfigWarehouseLocationDO warehouseDO = configWarehouseLocationService.getConfigWarehouseLocation(locationDO.getParentId());
        if(warehouseDO == null)
            throw exception0(CONFIG_WAREHOUSE_LOCATION_NOT_EXISTS.getCode(), "库位编码对应的仓库不存在，请联系管理员处理！");
        if(!warehouseDO.getCode().equals(cfgLocationCode))
            throw exception0(CONFIG_WAREHOUSE_LOCATION_NOT_EXISTS.getCode(), "您归库的样品不该进入此库，请检查后再重新归库。应归入仓库（编码）：" + cfgLocationCode);
        //判断归库码
        Integer isGenerateSimpleCode = configSubSampleDO.getIsGenerateSimpleCode();
        Integer printFlag = 0;
        if(1 == isGenerateSimpleCode){
            //生成归库码
            if(businessSubSampleDO.getIsGenerateReturnCode() == 0){
                String simpleCodeRule = configSubSampleDO.getSimpleCodeRule();
                String simpleCode = sequenceUtil.genCode(simpleCodeRule);
                businessSubSampleDO.setSampleReturnCode(simpleCode);
                businessSubSampleDO.setIsGenerateReturnCode(1);
                printFlag = 1;
            }
        }



        //更新入库状态
        businessSubSampleDO.setReturnStatus(QmsCommonConstant.COMPLETED);
        businessSubSampleDO.setConfigWarehouseLocationInfomationId(locationDO.getId());
        businessSubSampleDO.setReturnTime(LocalDateTime.now());
        businessSubSampleMapper.updateById(businessSubSampleDO);

        //更新流转记录 T_BSN_HND_RCD_SB。这不记录送样人、收样人。在调拨和归还时需要记录
        BusinessHandoverRecordSubSaveReqVO recordSubVO = new BusinessHandoverRecordSubSaveReqVO();
        recordSubVO.setBusinessSubSampleId(businessSubSampleDO.getId());
        recordSubVO.setSampleFlowNodeKey(QmsCommonConstant.FLOW_SAMPLE_STORAGE);
        recordSubVO.setSampleCode(businessSubSampleDO.getSampleReturnCode());
        recordSubVO.setOperationTime(LocalDateTime.now());
        recordSubVO.setOperator(loginUserName);
        recordSubVO.setOperatorId(loginUser.getId());
        recordSubVO.setSendSampleOperator("");
        recordSubVO.setReceiveSampleOperator("");
        recordSubVO.setConfigSampleFlowId(0L);
        businessHandoverRecordSubService.createBusinessHandoverRecordSub(recordSubVO);
        /*
        * 样品编码用归库码
        * 这里不更新交接人。 调拨和归还时记录交接人
        *
        * */
        BusinessSubSampleExtendRespVO respVO = BeanUtils.toBean(businessSubSampleDO, BusinessSubSampleExtendRespVO.class);
        respVO.setIsPrint(printFlag);
        respVO.setWarehouseName(warehouseDO.getName());
        respVO.setWarehouseLocationCode(locationDO.getCode());
        return respVO;
    }

    //样品下架
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer execTakeOff(JSONObject reqVo) {
        String actionWay = reqVo.getString("actionWay");
        String warehouseLocationCode = reqVo.getString("locationCode");
        String sampleReturnCode = reqVo.getString("sampleReturnCodes");
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        String loginUserName = SecurityFrameworkUtils.getLoginUserNickname();
        //查询要操作的样品
        LambdaQueryWrapper<BusinessSubSampleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessSubSampleDO::getSampleFlowNodeKey, QmsCommonConstant.FLOW_SAMPLE_STORAGE);
        queryWrapper.eq(BusinessSubSampleDO::getReturnStatus, QmsCommonConstant.COMPLETED);
        if(QmsWarehouseLocationConstant.SAMPLE_TAKE_OFF_ACTION_WAY_SAMPLE.equals(actionWay)){
            //按编号查询样品
            if(ObjectUtils.isEmpty(sampleReturnCode))
                throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "缺少样品编号参数！");
            List<String> sampleReturnCodes = Arrays.asList(sampleReturnCode.split( ","));
            queryWrapper.in(BusinessSubSampleDO::getSampleReturnCode, sampleReturnCodes);
        }
        else if(QmsWarehouseLocationConstant.SAMPLE_TAKE_OFF_ACTION_WAY_LOCATION.equals(actionWay)){
            //按库位查询样品
            if(ObjectUtils.isEmpty(warehouseLocationCode))
                throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "缺少库位编码参数！");
            ConfigWarehouseLocationDO locationDO = configWarehouseLocationService.getLocationByCode(warehouseLocationCode, QmsWarehouseLocationConstant.WAREHOUSE_TYPE_SAMPLE);
            if(locationDO == null)
                throw exception(CONFIG_WAREHOUSE_LOCATION_NOT_EXISTS);
            queryWrapper.eq(BusinessSubSampleDO::getConfigWarehouseLocationInfomationId, locationDO.getId());
        }else{
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "actionWay参数错误！");
        }
        List<BusinessSubSampleDO> waitingList = businessSubSampleMapper.selectList(queryWrapper);
        if(waitingList.isEmpty())
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "无待下架的样品！");
        Integer sampleCount = waitingList.size();

        //创建交接抬头
        BusinessSampleHandoverSaveReqVO handoverVO = new BusinessSampleHandoverSaveReqVO();
        String code = sequenceUtil.genCode("QMS_SAMPLE_TAKE_OFF_SERIAL");
        handoverVO.setCode(code);
        handoverVO.setName("样品下架记录");
        handoverVO.setSampleFlowNodeKey(QmsCommonConstant.FLOW_SAMPLE_STORAGE);
        handoverVO.setOperationTime(LocalDateTime.now());
        handoverVO.setOperator(loginUserName);
        handoverVO.setOperatorId(loginUser.getId());
        handoverVO.setOperationType(SAMPLE_STORAGE_OPERATION_TYPE_TAKEN_OFF);
        BusinessSampleHandoverRespVO handoverRespVO = businessSampleHandoverService.createBusinessSampleHandover(handoverVO);
        List<Long> dictionaryBusinessIdList = waitingList.stream().map(m -> m.getDictionaryBusinessId()).distinct().collect(Collectors.toList());
        List<DictionaryBusinessDO> dictionaryBusinessList = dictionaryBusinessMapper.selectByIds(dictionaryBusinessIdList);
        //更新下架状态
        List<BusinessHandoverRecordSubDO> recordList = new ArrayList<>();
        List<BusinessSampleHandoverDetailDO> detailList = new ArrayList<>();    //通过样品交接明细记录下架记录
        for(BusinessSubSampleDO businessSubSampleDO : waitingList){
            businessSubSampleDO.setReturnStatus(QmsCommonConstant.TAKEN_OFF);
            //创建流转记录
            BusinessHandoverRecordSubDO record = new BusinessHandoverRecordSubDO();
            record.setBusinessSubSampleId(businessSubSampleDO.getId());
            record.setSampleFlowNodeKey(QmsCommonConstant.FLOW_SAMPLE_STORAGE);
            record.setSampleCode(businessSubSampleDO.getSampleReturnCode());
            record.setOperationTime(LocalDateTime.now());
            record.setOperator(loginUserName);
            record.setOperatorId(loginUser.getId());
            record.setSendSampleOperator("");
            record.setReceiveSampleOperator("");
            record.setConfigSampleFlowId(0L);
            recordList.add(record);


            BusinessSampleHandoverDetailDO detailDO = new BusinessSampleHandoverDetailDO();
            detailDO.setBusinessSampleHandoverId(handoverRespVO.getId());
            detailDO.setBusinessSubSampleId(businessSubSampleDO.getId());
            detailDO.setSampleName(businessSubSampleDO.getSampleName());
            detailDO.setSampleCode(businessSubSampleDO.getSampleReturnCode());
            detailDO.setDictionaryBusinessId(businessSubSampleDO.getDictionaryBusinessId());
            DictionaryBusinessDO dictionaryBusiness = dictionaryBusinessList.stream().filter(f -> f.getId().equals(businessSubSampleDO.getDictionaryBusinessId())).findFirst().orElse(null);
            detailDO.setDictionaryBusinessName("");
            if(dictionaryBusiness != null)
                detailDO.setDictionaryBusinessName(dictionaryBusiness.getName());
            detailList.add(detailDO);
        }
        businessHandoverRecordSubService.insertBatch(recordList);
        businessSampleHandoverDetailService.insertBatch(detailList);
        businessSubSampleMapper.updateBatch(waitingList);
        return sampleCount;
    }

    //库位变更
    @Override
    public Integer execChangeLocation(JSONObject reqVo) {
        String actionWay = reqVo.getString("actionWay");
        String targetLocation = reqVo.getString("targetLocation");
        String warehouseLocationCode = reqVo.getString("warehouseLocationCode");
        String sampleReturnCode = reqVo.getString("sampleReturnCode");
        if(ObjectUtils.isEmpty(targetLocation))
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "缺少“变更后库位”参数！");
        ConfigWarehouseLocationDO targetLocationDO = configWarehouseLocationService.getLocationByCode(targetLocation, QmsWarehouseLocationConstant.WAREHOUSE_TYPE_SAMPLE);
        if(targetLocationDO == null)
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "“变更后库位”不存在，请检查编码是否正确！");
        //查询要操作的样品
        LambdaQueryWrapper<BusinessSubSampleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessSubSampleDO::getSampleFlowNodeKey, QmsCommonConstant.FLOW_SAMPLE_STORAGE);
        queryWrapper.eq(BusinessSubSampleDO::getReturnStatus, QmsCommonConstant.COMPLETED);
        if(QmsWarehouseLocationConstant.SAMPLE_TAKE_OFF_ACTION_WAY_SAMPLE.equals(actionWay)){
            //按编号查询样品
            if(ObjectUtils.isEmpty(sampleReturnCode))
                throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "缺少样品编号参数！");
            List<String> sampleReturnCodes = Arrays.asList(sampleReturnCode.split( ","));
            queryWrapper.in(BusinessSubSampleDO::getSampleReturnCode, sampleReturnCodes);
        }
        else if(QmsWarehouseLocationConstant.SAMPLE_TAKE_OFF_ACTION_WAY_LOCATION.equals(actionWay)){
            //按库位查询样品
            if(ObjectUtils.isEmpty(warehouseLocationCode))
                throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "缺少库位编码参数！");
            ConfigWarehouseLocationDO locationDO = configWarehouseLocationService.getLocationByCode(warehouseLocationCode, QmsWarehouseLocationConstant.WAREHOUSE_TYPE_SAMPLE);
            if(locationDO == null)
                throw exception(CONFIG_WAREHOUSE_LOCATION_NOT_EXISTS);
            queryWrapper.eq(BusinessSubSampleDO::getConfigWarehouseLocationInfomationId, locationDO.getId());
        }else{
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "actionWay参数错误！");
        }
        List<BusinessSubSampleDO> waitingList = businessSubSampleMapper.selectList(queryWrapper);
        if(waitingList.isEmpty())
            throw exception0(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "没有找到样品！");
        Integer sampleCount = waitingList.size();
        for(BusinessSubSampleDO businessSubSampleDO : waitingList){
            businessSubSampleDO.setConfigWarehouseLocationInfomationId(targetLocationDO.getId());
        }
        businessSubSampleMapper.updateBatch(waitingList);
        return sampleCount;
    }
}