package com.xinelu.manage.service.specialdiseaseroute.impl;

import com.alibaba.fastjson2.JSONObject;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.constant.TaskNodeTypeConstants;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.enums.ReleaseStatusEnum;
import com.xinelu.common.enums.RouteCheckStatusEnum;
import com.xinelu.common.enums.RouteNodeNameEnum;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.bean.BeanUtils;
import com.xinelu.common.utils.codes.GenerateSystemCodeUtil;
import com.xinelu.manage.domain.agency.Agency;
import com.xinelu.manage.domain.scriptInfo.ScriptInfo;
import com.xinelu.manage.domain.specialdiseasenode.SpecialDiseaseNode;
import com.xinelu.manage.domain.specialdiseaseroute.SpecialDiseaseRoute;
import com.xinelu.manage.domain.specialdiseaseroutepackage.SpecialDiseaseRoutePackage;
import com.xinelu.manage.domain.specialdiseasetriggercondition.SpecialDiseaseTriggerCondition;
import com.xinelu.manage.domain.textmessage.TextMessage;
import com.xinelu.manage.domain.wechattemplate.WechatTemplate;
import com.xinelu.manage.dto.specialdiseaseroute.SpecialDiseaseRouteDTO;
import com.xinelu.manage.mapper.agency.AgencyMapper;
import com.xinelu.manage.mapper.scriptInfo.ScriptInfoMapper;
import com.xinelu.manage.mapper.specialdiseasenode.SpecialDiseaseNodeMapper;
import com.xinelu.manage.mapper.specialdiseaseroute.SpecialDiseaseRouteMapper;
import com.xinelu.manage.mapper.specialdiseaseroutepackage.SpecialDiseaseRoutePackageMapper;
import com.xinelu.manage.mapper.specialdiseasetriggercondition.SpecialDiseaseTriggerConditionMapper;
import com.xinelu.manage.mapper.textmessage.TextMessageMapper;
import com.xinelu.manage.mapper.wechattemplate.WechatTemplateMapper;
import com.xinelu.manage.service.propagandainfo.IPropagandaInfoService;
import com.xinelu.manage.service.questioninfo.IQuestionInfoService;
import com.xinelu.manage.service.specialdiseaseroute.ISpecialDiseaseRouteService;
import com.xinelu.manage.vo.department.DepartmentBaseVo;
import com.xinelu.manage.vo.department.DepartmentVO;
import com.xinelu.manage.vo.propagandainfo.PropagandaMaterialsVo;
import com.xinelu.manage.vo.questionInfo.QuestionVO;
import com.xinelu.manage.vo.signpatientmanageroutenode.SignPatientManageNodeAuditVo;
import com.xinelu.manage.vo.specialdiseasenode.RouteTaskAuditVo;
import com.xinelu.manage.vo.specialdiseasenode.SpecialDiseaseNodeVO;
import com.xinelu.manage.vo.specialdiseaseroute.OriginalSpecialDiseaseRoute;
import com.xinelu.manage.vo.specialdiseaseroute.SpecialDiseaseRouteAuditVo;
import com.xinelu.manage.vo.specialdiseaseroute.SpecialDiseaseRouteInfoVo;
import com.xinelu.manage.vo.specialdiseaseroute.SpecialDiseaseRouteVO;
import com.xinelu.manage.vo.specialdiseaseroutepackage.SpecialDiseaseRoutePackageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 专病路径信息Service业务层处理
 *
 * @author xinelu
 * @date 2024-03-13
 */
@Slf4j
@Service
public class SpecialDiseaseRouteServiceImpl implements ISpecialDiseaseRouteService {
    @Resource
    private SpecialDiseaseRouteMapper specialDiseaseRouteMapper;
    @Resource
    private SpecialDiseaseNodeMapper specialDiseaseNodeMapper;
    @Resource
    private SpecialDiseaseTriggerConditionMapper triggerConditionMapper;
    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;
    @Resource
    private SpecialDiseaseRoutePackageMapper specialDiseaseRoutePackageMapper;
    @Resource
    private AgencyMapper agencyMapper;
    @Resource
    private ScriptInfoMapper scriptInfoMapper;
    @Resource
    private IQuestionInfoService questionInfoService;
    @Resource
    private IPropagandaInfoService propagandaInfoService;
    @Resource
    private TextMessageMapper textMessageMapper;
    @Resource
    private WechatTemplateMapper wechatTemplateMapper;
    @Resource
    private SpecialDiseaseTriggerConditionMapper specialDiseaseTriggerConditionMapper;

    /**
     * 查询专病路径信息
     *
     * @param id 专病路径信息主键
     * @return 专病路径信息
     */
    @Override
    public SpecialDiseaseRouteVO selectSpecialDiseaseRouteById(Long id) {
        return specialDiseaseRouteMapper.selectSpecialDiseaseRouteAndTriggerById(id);
    }

	@Override public SpecialDiseaseRouteInfoVo getById(Long id) {
		return specialDiseaseRouteMapper.getRouteAndChild(id);
	}

    /**
     * 查询专病路径信息列表
     *
     * @param specialDiseaseRoute 专病路径信息
     * @return 专病路径信息
     */
    @Override
    public List<SpecialDiseaseRouteVO> selectSpecialDiseaseRouteList(SpecialDiseaseRouteDTO specialDiseaseRoute) {
        return specialDiseaseRouteMapper.selectDiseaseRouteList(specialDiseaseRoute);
    }

    /**
     * 新增专病路径信息及服务包信息
     *
     * @param specialDiseaseRoute 专病路径信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertSpecialDiseaseRoute(SpecialDiseaseRouteVO specialDiseaseRoute) {
        //判断名称重复
        List<SpecialDiseaseRoute> specialDiseaseRoutes = specialDiseaseRouteMapper.selectCountByName(specialDiseaseRoute.getDepartmentId(), specialDiseaseRoute.getRouteName());
        if (CollectionUtils.isNotEmpty(specialDiseaseRoutes)) {
            return AjaxResult.error("路径名称 '" + specialDiseaseRoute.getRouteName() + "' 重复！");
        }
        specialDiseaseRoute.setCreateTime(LocalDateTime.now());
        specialDiseaseRoute.setCreateBy(SecurityUtils.getUsername());
        specialDiseaseRoute.setRouteCode(Constants.ROUTE_CODE + generateSystemCodeUtil.generateSystemCode(Constants.ROUTE_CODE));
        int insertRouteCount = specialDiseaseRouteMapper.insertSpecialDiseaseRoute(specialDiseaseRoute);
        if (insertRouteCount < 0) {
            return AjaxResult.error("新增专病路径信息失败，请联系管理员！");
        }
        //服务包
        List<SpecialDiseaseRoutePackage> specialDiseaseRoutePackages = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(specialDiseaseRoute.getRoutePackageList())) {
            for (SpecialDiseaseRoutePackage specialDiseaseRoutePackage : specialDiseaseRoute.getRoutePackageList()) {
                SpecialDiseaseRoutePackage routePackage = new SpecialDiseaseRoutePackage();
                specialDiseaseRoutePackage.setRouteId(specialDiseaseRoute.getId());
                specialDiseaseRoutePackage.setRouteName(specialDiseaseRoute.getRouteName());
                specialDiseaseRoutePackage.setCreateTime(LocalDateTime.now());
                specialDiseaseRoutePackage.setCreateBy(SecurityUtils.getUsername());
                BeanUtils.copyBeanProp(routePackage, specialDiseaseRoutePackage);
                specialDiseaseRoutePackages.add(routePackage);
            }
            int insertRoutePackageCount = specialDiseaseRoutePackageMapper.insertSpecialDiseaseRoutePackageList(specialDiseaseRoutePackages);
            if (insertRoutePackageCount < 0) {
                return AjaxResult.error("新增专病路径信息失败，请联系管理员！");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改专病路径信息及服务包信息
     *
     * @param specialDiseaseRoute 专病路径信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateSpecialDiseaseRoute(SpecialDiseaseRouteVO specialDiseaseRoute) {
        //判断名称重复
        List<SpecialDiseaseRoute> specialDiseaseRoutes = specialDiseaseRouteMapper.selectCountByName(specialDiseaseRoute.getDepartmentId(), specialDiseaseRoute.getRouteName());
        if (CollectionUtils.isNotEmpty(specialDiseaseRoutes)) {
            List<SpecialDiseaseRoute> collect = specialDiseaseRoutes.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getId()) && !specialDiseaseRoute.getId().equals(item.getId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                return AjaxResult.error("路径名称 '" + specialDiseaseRoute.getRouteName() + "' 重复！");
            }
        }
        int deleteRoutePackageCount = specialDiseaseRoutePackageMapper.deleteSpecialDiseaseRoutePackageByRouteId(specialDiseaseRoute.getId());
        if (deleteRoutePackageCount < 0) {
            return AjaxResult.error("修改专病路径信息失败，请联系管理员！");
        }
        specialDiseaseRoute.setUpdateTime(LocalDateTime.now());
        specialDiseaseRoute.setUpdateBy(SecurityUtils.getUsername());
        int updateRouteCount = specialDiseaseRouteMapper.updateSpecialDiseaseRoute(specialDiseaseRoute);
        if (updateRouteCount < 0) {
            return AjaxResult.error("修改专病路径信息失败，请联系管理员！");
        }
        List<SpecialDiseaseRoutePackage> specialDiseaseRoutePackages = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(specialDiseaseRoute.getRoutePackageList())) {
            for (SpecialDiseaseRoutePackageVO specialDiseaseRoutePackage : specialDiseaseRoute.getRoutePackageList()) {
                SpecialDiseaseRoutePackage routePackage = new SpecialDiseaseRoutePackage();
                specialDiseaseRoutePackage.setRouteId(specialDiseaseRoute.getId());
                specialDiseaseRoutePackage.setRouteName(specialDiseaseRoute.getRouteName());
                specialDiseaseRoutePackage.setUpdateTime(LocalDateTime.now());
                specialDiseaseRoutePackage.setUpdateBy(SecurityUtils.getUsername());
                BeanUtils.copyBeanProp(routePackage, specialDiseaseRoutePackage);
                specialDiseaseRoutePackages.add(routePackage);
            }
            int insertRoutePackageCount = specialDiseaseRoutePackageMapper.insertSpecialDiseaseRoutePackageList(specialDiseaseRoutePackages);
            if (insertRoutePackageCount < 0) {
                return AjaxResult.error("修改专病路径信息失败，请联系管理员！");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除专病路径信息
     *
     * @param ids 需要删除的专病路径信息主键
     * @return 结果
     */
    @Override
    public int deleteSpecialDiseaseRouteByIds(Long[] ids) {
        return specialDiseaseRouteMapper.deleteSpecialDiseaseRouteByIds(ids);
    }

    /**
     * 删除专病路径信息信息
     *
     * @param id 专病路径信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteSpecialDiseaseRouteById(Long id) {
        int deleteRouteCount = specialDiseaseRouteMapper.deleteSpecialDiseaseRouteById(id);
        if (deleteRouteCount < 0) {
            throw new ServiceException("删除专病路径管理信息失败，请联系管理员！");
        }
        int deleteNodeCount = specialDiseaseNodeMapper.deleteSpecialDiseaseNodeByRouteId(id);
        if (deleteNodeCount < 0) {
            throw new ServiceException("删除专病路径管理信息失败，请联系管理员！");
        }
        int deleteTriggerConditionCount = triggerConditionMapper.deleteSpecialDiseaseTriggerConditionByRouteId(id);
        if (deleteTriggerConditionCount < 0) {
            throw new ServiceException("删除专病路径管理信息失败，请联系管理员！");
        }
        int deleteRoutePackageCount = specialDiseaseRoutePackageMapper.deleteSpecialDiseaseRoutePackageByRouteId(id);
        if (deleteRoutePackageCount < 0) {
            return AjaxResult.error("删除专病路径管理信息失败，请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 科室路径数量
     *
     * @param specialDiseaseRouteQueryDto 查询条件
     * @return AjaxResult
     */
    @Override
    public AjaxResult departmentRouteCount(SpecialDiseaseRouteDTO specialDiseaseRouteQueryDto) {
        List<DepartmentVO> departmentVOS = specialDiseaseRouteMapper.departmentRouteByDepartmentName(specialDiseaseRouteQueryDto);
	    Agency agency = agencyMapper.selectAgencyById(specialDiseaseRouteQueryDto.getHospitalAgencyId());
		return AjaxResult.success(DepartmentBaseVo.builder().hospitalAgencyName(ObjectUtils.isEmpty(agency) ? "" : agency.getAgencyName())
			.deptNumList(departmentVOS).build());
    }

    /**
     * 专病路径发布
     *
     * @param specialDiseaseRoute 路径信息
     * @return AjaxResult
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editReleaseStatus(SpecialDiseaseRoute specialDiseaseRoute) {
        if (Objects.isNull(specialDiseaseRoute) || StringUtils.isBlank(specialDiseaseRoute.getReleaseStatus()) || Objects.isNull(specialDiseaseRoute.getId())) {
            throw new ServiceException("请选择需要发布专病路径的信息！");
        }
	    List<String> checkStatusList = new ArrayList<>();
        if (StringUtils.equals(ReleaseStatusEnum.PUBLISHED.getInfo(), specialDiseaseRoute.getReleaseStatus())) {
	        checkStatusList = specialDiseaseRouteMapper.selectRouteCheckStatus(specialDiseaseRoute.getId());
            if (CollectionUtils.isEmpty(checkStatusList)) {
	            throw new ServiceException("该路径无节点，请先增加节点并审核通过后发布！");
            }
			// 判断子路径是否都审核通过---子路径都包含节点并且审核通过，主路径才能发布
	        List<SpecialDiseaseRouteInfoVo> childRouteList = specialDiseaseRouteMapper.getChildList(specialDiseaseRoute.getId());
	        List<String> finalCheckStatus = checkStatusList;
	        childRouteList.forEach(childRoute -> {
		        List<String> checkStatus1 = specialDiseaseRouteMapper.selectRouteCheckStatus(childRoute.getSpecialDiseaseRouteId());
		        if (CollectionUtils.isEmpty(checkStatus1)) {
			        throw new ServiceException("存在无节点的子路径，请先增加节点并审核通过后发布！");
		        }
		        finalCheckStatus.addAll(checkStatus1);
	        });

	        for (String checkStatus : finalCheckStatus) {
		        if (!StringUtils.equals(RouteCheckStatusEnum.AGREE.getInfo(), checkStatus)) {
			        throw new ServiceException("该路径存在未审核通过的节点，请全部审核通过后发布！");
		        }
	        }
        }

        if (ReleaseStatusEnum.UNPUBLISHED.getInfo().equals(specialDiseaseRoute.getReleaseStatus())) {
            specialDiseaseRoute.setReleaseStatus(ReleaseStatusEnum.REVOKE.getInfo());
        }
        specialDiseaseRoute.setUpdateTime(LocalDateTime.now());
        specialDiseaseRoute.setUpdateBy(SecurityUtils.getUsername());
        return specialDiseaseRouteMapper.updateSpecialDiseaseRoute(specialDiseaseRoute);
    }

	/**
	 * 路径审核->路径信息获取主路径及子路径信息及节点
	 * @param routeId 主路径主键
	 * @return 主路径信息及节点、子路径信息及节点
	 */
	@Override
	public SpecialDiseaseRouteAuditVo getRouteAuditInfo(Long routeId) {
		return specialDiseaseRouteMapper.getRouteAuditInfo(routeId);
	}

	/**
	 * 路径详情->路径任务，节点详细信息
	 * @param id 签约记录主键
	 * @return 节点详细信息列表
	 * @author haown
	 * @date 2024-07-26 16:00
	 */
	@Override
	public List<SignPatientManageNodeAuditVo> getRouteNodeInfo(Long id) {
		List<SignPatientManageNodeAuditVo> manageNodeAuditList = new ArrayList<>();
		SpecialDiseaseRoute specialDiseaseRoute = specialDiseaseRouteMapper.selectSpecialDiseaseRouteById(id);
		// 查询主路径及子路径节点
		List<RouteTaskAuditVo> nodeList = specialDiseaseNodeMapper.getByParentRouteId(id);

		// 组装数据
		nodeList.forEach(node -> {
			SignPatientManageNodeAuditVo manageRouteNode = new SignPatientManageNodeAuditVo();
			BeanUtils.copyBeanProp(manageRouteNode, node);
			manageRouteNode.setManageRouteName(specialDiseaseRoute.getRouteName());
			manageRouteNode.setId(null);
			manageRouteNode.setRouteNodeId(node.getId());
			manageRouteNode.setExecuteTime(node.getExecutionTime());
			manageRouteNode.setRouteNodeNameCN(RouteNodeNameEnum.getNameByInfo(node.getRouteNodeName()).getName());

			JSONObject templateDetail = new JSONObject();
			// 根据模板类型，存放模板字段
			if (StringUtils.isNotBlank(node.getTaskNodeType())) {
				switch (node.getTaskNodeType()) {
					// 宣教
					case TaskNodeTypeConstants.PROPAGANDA_ARTICLE:
						manageRouteNode.setPropagandaInfoId(node.getTemplateId());
						manageRouteNode.setPropagandaTitle(node.getTemplateName());
						// 查询宣教表
						if (manageRouteNode.getPropagandaInfoId() != null) {
							PropagandaMaterialsVo propagandaMaterialsVo = propagandaInfoService.selectPropagandaInfoById(node.getTemplateId());
							if (ObjectUtils.isNotEmpty(propagandaMaterialsVo)) {
								templateDetail = JSONObject.parseObject(JSONObject.toJSONString(propagandaMaterialsVo));
								manageRouteNode.setTemplateDetail(templateDetail);
							}
						}
						break;
					// 问卷
					case TaskNodeTypeConstants.QUESTIONNAIRE_SCALE:
						manageRouteNode.setQuestionInfoId(node.getTemplateId());
						manageRouteNode.setQuestionnaireName(node.getTemplateName());
						// 查询问卷详情
						QuestionVO questionVO = questionInfoService.selectQuestionInfoById(node.getTemplateId());
						if (ObjectUtils.isNotEmpty(questionVO)) {
							templateDetail = JSONObject.parseObject(JSONObject.toJSONString(questionVO));
							manageRouteNode.setTemplateDetail(templateDetail);
						}
						break;
					// 话术
					case TaskNodeTypeConstants.PHONE_OUTBOUND:
						manageRouteNode.setScriptInfoId(node.getScriptInfoId());
						// 查询话术
						ScriptInfo scriptInfo = scriptInfoMapper.selectScriptInfoById(node.getScriptInfoId());
						if (ObjectUtils.isNotEmpty(scriptInfo)) {
							// 话术库json内容替换
							manageRouteNode.setPhoneNodeContent(scriptInfo.getFlowScheme());
							templateDetail = JSONObject.parseObject(JSONObject.toJSONString(scriptInfo));
							manageRouteNode.setTemplateDetail(templateDetail);
						}
						break;
				}
			}
			// 查询短信、公众号、小程序内容
			if (node.getMessageTemplateId() != null) {
				// 替换短信模板
				TextMessage textMessage = textMessageMapper.selectTextMessageById(node.getMessageTemplateId());
				manageRouteNode.setMessageNodeContent(ObjectUtils.isEmpty(textMessage) ? "" : textMessage.getTextMessageContent());
			}
			if (node.getPhoneMessageTemplateId() != null) {
				// 替换短信模板
				TextMessage textMessage = textMessageMapper.selectTextMessageById(node.getPhoneMessageTemplateId());
				manageRouteNode.setPhoneMessageTemplateContent(ObjectUtils.isEmpty(textMessage) ? "" : textMessage.getTextMessageContent());
			}
			// 替换公众号模板
			if (node.getOfficialPushSign() != null && node.getOfficialPushSign() == 1) {
				WechatTemplate wechatTemplate = wechatTemplateMapper.selectWechatTemplateById(node.getOfficialTemplateId());
				manageRouteNode.setOfficialNodeContent(ObjectUtils.isEmpty(wechatTemplate) ? "" : wechatTemplate.getTemplateContent());
			}
			// 替换小程序模板
			if (node.getAppletPushSign() != null && node.getAppletPushSign() == 1) {
				WechatTemplate wechatTemplate = wechatTemplateMapper.selectWechatTemplateById(node.getAppletTemplateId());
				manageRouteNode.setAppletNodeContent(ObjectUtils.isEmpty(wechatTemplate) ? "" : wechatTemplate.getTemplateContent());
			}
			manageNodeAuditList.add(manageRouteNode);
		});
		return manageNodeAuditList;
	}

    /**
     * 克隆节点路径
     *
     * @param id 路径id
     * @return AjaxResult
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult cloneRoute(Long id) {
        //主路径
        SpecialDiseaseRoute specialDiseaseRoute = specialDiseaseRouteMapper.selectSpecialDiseaseRouteById(id);
        specialDiseaseRoute.setId(null);
        specialDiseaseRoute.setRouteCode(Constants.ROUTE_CODE + generateSystemCodeUtil.generateSystemCode(Constants.ROUTE_CODE));
        specialDiseaseRoute.setRouteName(specialDiseaseRoute.getRouteName() + "-副本");
        specialDiseaseRoute.setCreateBy(SecurityUtils.getUsername());
        specialDiseaseRoute.setReleaseStatus(ReleaseStatusEnum.UNPUBLISHED.getInfo());
        specialDiseaseRoute.setCreateTime(LocalDateTime.now());
        specialDiseaseRoute.setUpdateBy(null);
        specialDiseaseRoute.setUpdateTime(null);
        //判断名称重复
        extracted(specialDiseaseRoute, id);
        int routeCount = specialDiseaseRouteMapper.insertSpecialDiseaseRoute(specialDiseaseRoute);
        if (routeCount <= 0) {
            log.info("新增主路径失败！");
            throw new ServiceException("克隆失败！");
        }
        //子路径查询新增
        List<Long> specialDiseaseRouteIds = new ArrayList<>();
        List<OriginalSpecialDiseaseRoute> childSpecialDiseaseRoute = specialDiseaseRouteMapper.getChildSpecialDiseaseRoute(id);
        if (CollectionUtils.isNotEmpty(childSpecialDiseaseRoute)) {
            specialDiseaseRouteIds = childSpecialDiseaseRoute.stream().filter(Objects::nonNull).map(SpecialDiseaseRoute::getId).filter(Objects::nonNull).collect(Collectors.toList());
            childSpecialDiseaseRoute.forEach(item -> {
                item.setParentRouteId(specialDiseaseRoute.getId());
                item.setRouteCode(Constants.ROUTE_CODE + generateSystemCodeUtil.generateSystemCode(Constants.ROUTE_CODE));
                item.setReleaseStatus(ReleaseStatusEnum.UNPUBLISHED.getInfo());
                item.setCreateBy(SecurityUtils.getUsername());
                item.setCreateTime(LocalDateTime.now());
            });
            int childCount = specialDiseaseRouteMapper.insertSpecialDiseaseRouteList(childSpecialDiseaseRoute);
            if (childCount <= 0) {
                log.info("新增子路径失败！");
                throw new ServiceException("克隆失败！");
            }
        }
        //主路径节点
        List<SpecialDiseaseNodeVO> specialDiseaseNodeList = new ArrayList<>();
        specialDiseaseRouteIds.add(id);
        List<SpecialDiseaseNode> specialDiseaseNodes = specialDiseaseNodeMapper.selectSpecialDiseaseNodes(specialDiseaseRouteIds);
        if (CollectionUtils.isNotEmpty(specialDiseaseNodes)) {
            for (SpecialDiseaseNode specialDiseaseNode : specialDiseaseNodes) {
                SpecialDiseaseNodeVO specialDiseaseNodeVO = new SpecialDiseaseNodeVO();
                BeanUtils.copyProperties(specialDiseaseNode, specialDiseaseNodeVO);
                if (specialDiseaseNode.getRouteId().equals(id)) {
                    specialDiseaseNodeVO.setRouteId(specialDiseaseRoute.getId());
                    specialDiseaseNodeVO.setRouteName(specialDiseaseRoute.getRouteName());
                } else {
                    OriginalSpecialDiseaseRoute originalSpecialDiseaseRoute = childSpecialDiseaseRoute.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getOriginalSpecialDiseaseRouteId()) && specialDiseaseNode.getRouteId().equals(item.getOriginalSpecialDiseaseRouteId())).findFirst().orElse(new OriginalSpecialDiseaseRoute());
                    specialDiseaseNodeVO.setRouteId(originalSpecialDiseaseRoute.getId());
                    specialDiseaseNodeVO.setRouteName(specialDiseaseNode.getRouteName());
                }
                specialDiseaseNodeVO.setId(null);
                specialDiseaseNodeVO.setRouteCheckStatus(null);
                specialDiseaseNodeVO.setRouteCheckPerson(null);
                specialDiseaseNodeVO.setRouteCheckDate(null);
                specialDiseaseNodeVO.setRouteCheckRemark(null);
                specialDiseaseNodeVO.setCreateBy(SecurityUtils.getUsername());
                specialDiseaseNodeVO.setCreateTime(LocalDateTime.now());
                specialDiseaseNodeList.add(specialDiseaseNodeVO);
            }
            int nodeCount = specialDiseaseNodeMapper.insertSpecialDiseaseNodeList(specialDiseaseNodeList);
            if (nodeCount < 0) {
                log.info("新增主路径节点失败！");
                throw new ServiceException("克隆失败！");
            }
        }
        SpecialDiseaseRoutePackage specialDiseaseRoutePackage = new SpecialDiseaseRoutePackage();
        specialDiseaseRoutePackage.setRouteId(id);
        List<SpecialDiseaseRoutePackage> specialDiseaseRoutePackages = specialDiseaseRoutePackageMapper.selectSpecialDiseaseRoutePackageList(specialDiseaseRoutePackage);
        if (CollectionUtils.isNotEmpty(specialDiseaseRoutePackages)) {
            specialDiseaseRoutePackages.forEach(item -> {
                item.setId(null);
                item.setRouteName(specialDiseaseRoute.getRouteName());
                item.setRouteId(specialDiseaseRoute.getId());
                item.setCreateBy(SecurityUtils.getUsername());
                item.setCreateTime(LocalDateTime.now());
            });
            int packageCount = specialDiseaseRoutePackageMapper.insertSpecialDiseaseRoutePackageList(specialDiseaseRoutePackages);
            if (packageCount < 0) {
                log.info("新增服务包失败！");
                throw new ServiceException("克隆失败！");
            }
            SpecialDiseaseTriggerCondition specialDiseaseTriggerCondition = new SpecialDiseaseTriggerCondition();
            specialDiseaseTriggerCondition.setRouteId(id);
            List<SpecialDiseaseTriggerCondition> specialDiseaseTriggerConditions = specialDiseaseTriggerConditionMapper.selectSpecialDiseaseTriggerConditionList(specialDiseaseTriggerCondition);
            if (CollectionUtils.isNotEmpty(specialDiseaseTriggerConditions)) {
                specialDiseaseTriggerConditions.forEach(item -> {
                    item.setId(null);
                    item.setRouteId(specialDiseaseRoute.getId());
                    item.setRouteName(specialDiseaseRoute.getRouteName());
                    item.setCreateBy(SecurityUtils.getUsername());
                    item.setCreateTime(LocalDateTime.now());
                });
                int conditionCount = specialDiseaseTriggerConditionMapper.insertTriggerConditionList(specialDiseaseTriggerConditions);
                if (conditionCount < 0) {
                    log.info("新增触发条件失败！");
                    throw new ServiceException("克隆失败！");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 数据组装
     *
     * @param specialDiseaseRoute 路径信息
     */
    private void extracted(SpecialDiseaseRoute specialDiseaseRoute, Long id) {
        List<SpecialDiseaseRoute> specialDiseaseRoutes = specialDiseaseRouteMapper.selectCountByName(specialDiseaseRoute.getDepartmentId(), specialDiseaseRoute.getRouteName());
        if (CollectionUtils.isNotEmpty(specialDiseaseRoutes)) {
            List<SpecialDiseaseRoute> collect = specialDiseaseRoutes.stream().filter(Objects::nonNull).filter(item -> Objects.nonNull(item.getId()) && !id.equals(item.getId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                specialDiseaseRoute.setRouteName(specialDiseaseRoute.getRouteName() + "-副本");
                extracted(specialDiseaseRoute, id);
            }
        }
    }
}
