package com.ruoyi.project.business.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceErrorException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ValidateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.jep.JEPUtils;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.business.domain.TpCaseElevator;
import com.ruoyi.project.business.domain.TpParaLibrary;
import com.ruoyi.project.business.domain.TpParaRelatedAction;
import com.ruoyi.project.business.domain.TpParaRelatedCase;
import com.ruoyi.project.business.domain.TpParaRelatedLogic;
import com.ruoyi.project.business.dto.Option;
import com.ruoyi.project.business.dto.TpCaseElevatorDto;
import com.ruoyi.project.business.dto.TpParaRelatedActionDto;
import com.ruoyi.project.business.dto.TpParaRelatedActionInfo;
import com.ruoyi.project.business.dto.TpParaRelatedCaseDto;
import com.ruoyi.project.business.dto.TpParaRelatedLogicDto;
import com.ruoyi.project.business.dto.TpParaRelatedLogicInfo;
import com.ruoyi.project.business.enums.ComputedFlagEnum;
import com.ruoyi.project.business.enums.DelFlagEnum;
import com.ruoyi.project.business.enums.EditableEnum;
import com.ruoyi.project.business.enums.InputTypeEnum;
import com.ruoyi.project.business.enums.JEPFuncEnum;
import com.ruoyi.project.business.enums.JEPLogicEnum;
import com.ruoyi.project.business.enums.JEPSplitEnum;
import com.ruoyi.project.business.enums.OperationEnum;
import com.ruoyi.project.business.enums.OperationFlagEnum;
import com.ruoyi.project.business.enums.RelationshipEnum;
import com.ruoyi.project.business.enums.StatusEnum;
import com.ruoyi.project.business.mapper.TpParaRelatedCaseMapper;
import com.ruoyi.project.business.service.ITpCaseElevatorService;
import com.ruoyi.project.business.service.ITpParaLibraryService;
import com.ruoyi.project.business.service.ITpParaRelatedActionService;
import com.ruoyi.project.business.service.ITpParaRelatedCaseService;
import com.ruoyi.project.business.service.ITpParaRelatedLogicService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author jubs
 */
@Service
@Slf4j
public class TpParaRelatedCaseServiceImpl extends ServiceImpl<TpParaRelatedCaseMapper, TpParaRelatedCase> implements
    ITpParaRelatedCaseService {

    @Resource
    private ITpCaseElevatorService iTpCaseElevatorService;

    @Resource
    private ITpParaRelatedLogicService iTpParaRelatedLogicService;

    @Resource
    private ITpParaRelatedActionService iTpParaRelatedActionService;

    @Resource
    private ITpParaLibraryService iTpParaLibraryService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveOrUpdateDto(TpParaRelatedCaseDto tpParaRelatedCase) {
        Integer operationFlag = tpParaRelatedCase.getOperationFlag();
        Date date = new Date();
        if (OperationFlagEnum.ADD.getFlag().equals(operationFlag)) {
            List<TpParaRelatedCase> list = list(
                Wrappers.<TpParaRelatedCase>lambdaQuery()
                    .eq(TpParaRelatedCase::getCaseName, tpParaRelatedCase.getCaseName())
                    .eq(TpParaRelatedCase::getDelFlag, DelFlagEnum.NORMAL.getValue())
            );
            if (list != null && list.size() > 0) {
                throw new ServiceErrorException(MessageUtils.message("relatedCase.notUnique"));
            }
            if (tpParaRelatedCase.getRelationEnters() == null || tpParaRelatedCase.getRelationEnters().size() == 0) {
                throw new ServiceErrorException(MessageUtils.message("relatedCase.atLeastModel"));
            }
            if (tpParaRelatedCase.getLogicList() == null || tpParaRelatedCase.getLogicList().size() == 0) {
                throw new ServiceErrorException(MessageUtils.message("relatedCase.atLeastCase"));
            }
            if (tpParaRelatedCase.getActionList() == null || tpParaRelatedCase.getActionList().size() == 0) {
                throw new ServiceErrorException(MessageUtils.message("relatedCase.atLeastResult"));
            }
            TpParaRelatedCase basicInfo = new TpParaRelatedCase();
            BeanUtils.copyBeanProp(basicInfo, tpParaRelatedCase);
            basicInfo.setStatus(StatusEnum.ENABLE.getCode());
            basicInfo.setCreateBy(SecurityUtils.getStrUserId());
            basicInfo.setCreateTime(date);
            save(basicInfo);

            tpParaRelatedCase.getRelationEnters().forEach(item -> {
                item.setRelatedCaseId(basicInfo.getId());
                item.setCreateBy(SecurityUtils.getStrUserId());
                item.setCreateTime(date);
            });
            List<TpCaseElevator> caseElevators = tpParaRelatedCase.getRelationEnters().stream().map(
                item -> {
                    TpCaseElevator caseElevator = new TpCaseElevator();
                    BeanUtils.copyBeanProp(caseElevator, item);
                    return caseElevator;
                }
            ).collect(Collectors.toList());

            iTpCaseElevatorService.saveBatch(caseElevators);

            tpParaRelatedCase.getLogicList().forEach(item -> {
                item.setCaseId(basicInfo.getId());
                item.setCreateBy(SecurityUtils.getStrUserId());
                item.setCreateTime(date);
            });
            List<TpParaRelatedLogic> logicList = tpParaRelatedCase.getLogicList().stream().map(item -> {
                TpParaRelatedLogic logic = new TpParaRelatedLogic();
                BeanUtils.copyBeanProp(logic, item);
                return logic;
            }).collect(Collectors.toList());
            iTpParaRelatedLogicService.saveBatch(logicList);

            tpParaRelatedCase.getActionList().forEach(item -> {
                item.setCaseId(basicInfo.getId());
                item.setCreateBy(SecurityUtils.getStrUserId());
                item.setCreateTime(date);
            });
            List<TpParaRelatedAction> actionList = tpParaRelatedCase.getActionList().stream().map(item -> {
                TpParaRelatedAction action = new TpParaRelatedAction();
                BeanUtils.copyBeanProp(action, item);
                return action;
            }).collect(Collectors.toList());

            iTpParaRelatedActionService.saveBatch(actionList);


        } else if (OperationFlagEnum.EDIT.getFlag().equals(operationFlag)) {
            TpParaRelatedCase sqlData = getById(tpParaRelatedCase.getId());
            if (sqlData == null) {
                //数据已被删除
                throw new ServiceErrorException(MessageUtils.message("common.dataDeleted"));
            }
            if (!ValidateUtils.allowUpdate(sqlData.getUpdateTime(), tpParaRelatedCase.getUpdateTime())) {
                throw new ServiceErrorException(MessageUtils.message("common.dataUpdated"));
            }
            BeanUtils.copyBeanProp(sqlData, tpParaRelatedCase);
            sqlData.setUpdateBy(SecurityUtils.getStrUserId());
            sqlData.setUpdateTime(date);

            List<Long> logicDeleteIds = tpParaRelatedCase.getLogicDeleteIds();

            List<Long> actionDeleteIds = tpParaRelatedCase.getActionDeleteIds();

            List<Long> relationEnterDeleteIds = tpParaRelatedCase.getRelationEnterDeleteIds();
            List<TpParaRelatedLogic> logicList;
            List<TpParaRelatedAction> actionList;
            List<TpCaseElevator> relationEnters;
            //处理删除部分
            if (logicDeleteIds != null && logicDeleteIds.size() > 0) {
                logicList = iTpParaRelatedLogicService.list(
                    Wrappers.<TpParaRelatedLogic>lambdaQuery()
                        .in(TpParaRelatedLogic::getId, logicDeleteIds)
                );
                if (logicList != null && logicList.size() > 0) {
                    logicList.forEach(item -> {
                        item.setUpdateBy(SecurityUtils.getStrUserId());
                        item.setUpdateTime(date);
                        item.setDelFlag(DelFlagEnum.DELETED.getValue());
                    });
                    iTpParaRelatedLogicService.updateBatchById(logicList);
                }
            }
            if (actionDeleteIds != null && actionDeleteIds.size() > 0) {
                actionList = iTpParaRelatedActionService.list(
                    Wrappers.<TpParaRelatedAction>lambdaQuery()
                        .in(TpParaRelatedAction::getId, actionDeleteIds)
                );
                if (actionList != null && actionList.size() > 0) {
                    actionList.forEach(item -> {
                        item.setUpdateBy(SecurityUtils.getStrUserId());
                        item.setUpdateTime(date);
                        item.setDelFlag(DelFlagEnum.DELETED.getValue());
                    });
                    iTpParaRelatedActionService.updateBatchById(actionList);
                }
            }
            if (relationEnterDeleteIds != null && relationEnterDeleteIds.size() > 0) {
                relationEnters = iTpCaseElevatorService.list(
                    Wrappers.<TpCaseElevator>lambdaQuery()
                        .in(TpCaseElevator::getId, relationEnterDeleteIds)
                );
                if (relationEnters != null && relationEnters.size() > 0) {
                    relationEnters.forEach(item -> {
                        item.setUpdateBy(SecurityUtils.getStrUserId());
                        item.setUpdateTime(date);
                        item.setDelFlag(DelFlagEnum.DELETED.getValue());
                    });
                    iTpCaseElevatorService.updateBatchById(relationEnters);
                }

            }

            //处理修改部分
            List<TpParaRelatedLogic> logicListNeedUpdate = tpParaRelatedCase.getLogicList().stream()
                .filter(item -> OperationFlagEnum.EDIT.getFlag().equals(item.getOperationFlag()))
                .collect(Collectors.toList());
            List<TpParaRelatedAction> actionListNeedUpdate = tpParaRelatedCase.getActionList().stream()
                .filter(item -> OperationFlagEnum.EDIT.getFlag().equals(item.getOperationFlag()))
                .collect(Collectors.toList());
            if (logicListNeedUpdate.size() > 0) {
                logicListNeedUpdate.forEach(item -> {
                    item.setUpdateBy(SecurityUtils.getStrUserId());
                    item.setUpdateTime(date);
                });
                iTpParaRelatedLogicService.updateBatchById(logicListNeedUpdate);
            }

            if (actionListNeedUpdate.size() > 0) {
                actionListNeedUpdate.forEach(item -> {
                    item.setUpdateBy(SecurityUtils.getStrUserId());
                    item.setUpdateTime(date);
                });
                iTpParaRelatedActionService.updateBatchById(actionListNeedUpdate);
            }

            //处理新增部分
            List<TpParaRelatedLogic> logicListNeedInsert = tpParaRelatedCase.getLogicList().stream()
                .filter(item -> OperationFlagEnum.ADD.getFlag().equals(item.getOperationFlag()))
                .collect(Collectors.toList());

            List<TpParaRelatedAction> actionListNeedInsert = tpParaRelatedCase.getActionList().stream()
                .filter(item -> OperationFlagEnum.ADD.getFlag().equals(item.getOperationFlag()))
                .collect(Collectors.toList());
            List<TpCaseElevator> relationEntersNeedInsert = tpParaRelatedCase.getRelationEnters().stream()
                .filter(item -> OperationFlagEnum.ADD.getFlag().equals(item.getOperationFlag()))
                .collect(Collectors.toList());
            if (logicListNeedInsert.size() > 0) {
                logicListNeedInsert.forEach(item -> {
                    item.setCreateBy(SecurityUtils.getStrUserId());
                    item.setCreateTime(date);
                    item.setCaseId(tpParaRelatedCase.getId());
                });
                iTpParaRelatedLogicService.saveBatch(logicListNeedInsert);
            }
            if (actionListNeedInsert.size() > 0) {
                actionListNeedInsert.forEach(item -> {
                    item.setCreateBy(SecurityUtils.getStrUserId());
                    item.setCreateTime(date);
                    item.setCaseId(tpParaRelatedCase.getId());
                });
                iTpParaRelatedActionService.saveBatch(actionListNeedInsert);
            }
            if (relationEntersNeedInsert.size() > 0) {
                relationEntersNeedInsert.forEach(item -> {
                    item.setCreateBy(SecurityUtils.getStrUserId());
                    item.setCreateTime(date);
                    item.setRelatedCaseId(tpParaRelatedCase.getId());
                });
                iTpCaseElevatorService.saveBatch(relationEntersNeedInsert);

            }

        } else {
            log.info("错误的操作标识符");
        }

        return 0;
    }


    @Override
    public TableDataInfo getTableList(TpParaRelatedCaseDto tpParaRelatedCaseDto) {
        List<TpParaRelatedCase> list = list(
            Wrappers.<TpParaRelatedCase>lambdaQuery()
                .eq(TpParaRelatedCase::getDelFlag, DelFlagEnum.NORMAL.getValue())
                .like(StringUtils.isNotBlank(tpParaRelatedCaseDto.getCaseName()), TpParaRelatedCase::getCaseName,
                    tpParaRelatedCaseDto.getCaseName())
                .eq(StringUtils.isNotBlank(tpParaRelatedCaseDto.getStatus()), TpParaRelatedCase::getStatus,
                    tpParaRelatedCaseDto.getStatus())
        );

        //设置分页属性
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());

        List<TpParaRelatedCaseDto> res = list.stream().map(item -> {
            TpParaRelatedCaseDto resultDto = new TpParaRelatedCaseDto();
            BeanUtils.copyBeanProp(resultDto, item);
            return resultDto;
        }).collect(Collectors.toList());

        List<Long> caseIds = res.stream().map(TpParaRelatedCaseDto::getId).collect(Collectors.toList());

        List<TpParaRelatedActionDto> actionList = iTpParaRelatedActionService.queryMoreInfo(caseIds);
        Map<Long, List<TpParaRelatedActionDto>> caseIdToActionMap = actionList.stream()
            .collect(Collectors.groupingBy(TpParaRelatedActionDto::getCaseId));

        List<TpParaRelatedLogicDto> logicList = iTpParaRelatedLogicService.queryMoreInfo(caseIds);
        Map<Long, List<TpParaRelatedLogicDto>> caseIdToLogicMap = logicList.stream()
            .collect(Collectors.groupingBy(TpParaRelatedLogic::getCaseId));

        //查询关联梯形数量
        List<TpCaseElevator> elevators = iTpCaseElevatorService.list(
            Wrappers.<TpCaseElevator>lambdaQuery()
                .in(TpCaseElevator::getRelatedCaseId, caseIds)
                .eq(TpCaseElevator::getDelFlag, DelFlagEnum.NORMAL.getValue())
        );
        Map<Long, List<TpCaseElevator>> countMap = elevators.stream()
            .collect(Collectors.groupingBy(TpCaseElevator::getRelatedCaseId));

        res.forEach(item -> {
            if (countMap.containsKey(item.getId())) {
                item.setElevatorCount(countMap.get(item.getId()).size());
            }

            List<TpParaRelatedActionDto> actions = caseIdToActionMap.get(item.getId());
            List<TpParaRelatedLogicDto> logics = caseIdToLogicMap.get(item.getId());
            StringBuilder logicStr = new StringBuilder();
            StringBuilder actionStr = new StringBuilder();

            //先拼装 条件内容
            if(ObjectUtils.isNotEmpty(logics)){
                for (int i = 0; i < logics.size(); i++) {
                    TpParaRelatedLogicDto logicDto = logics.get(i);
                    OperationEnum operationEnum = OperationEnum.fromByValue(logicDto.getOperation());
                    logicStr.append(logicDto.getParaName())
                            .append(" ")
                            .append(operationEnum.getName())
                            .append(" ")
                            .append(InputTypeEnum.SELECT.getCode().equals(logicDto.getInputType()) ? logicDto.getLabel()
                                    : logicDto.getValue());
                    if (i != logics.size() - 1) {
                        String andOrStr = " " +
                                (RelationshipEnum.ALL_MATCH.getCode().equals(item.getRelationship()) ? "AND" : "OR")
                                + " ";
                        logicStr.append(andOrStr);
                    }
                }
            }

            item.setLogicStr(logicStr.toString());
            //拼装 结果内容
            //回显公式
            List<String> paramsList = new ArrayList<>();
            if(ObjectUtils.isNotEmpty(actions)){
                for (TpParaRelatedActionDto data : actions) {
                    if (ComputedFlagEnum.YES.getCode().equals(data.getComputedFlag())) {
                        paramsList.addAll(JEPUtils.getParam(data.getValue()));
                    }
                }
            }
            Map<String, String> codeToNameMap = new HashMap<>();
            if (paramsList.size() > 0) {
                paramsList = paramsList.stream().distinct().sorted(
                    Comparator.comparingInt(String::length)
                ).collect(Collectors.toList());
                //查询所有的 参数
                List<TpParaLibrary> libraries = iTpParaLibraryService.list(
                    Wrappers.<TpParaLibrary>lambdaQuery()
                        .in(TpParaLibrary::getParaCode, paramsList)
                );

                if (libraries.size() > 0) {
                    codeToNameMap = libraries.stream().collect(Collectors
                        .toMap(TpParaLibrary::getParaCode, TpParaLibrary::getParaName));
                }
            }
            if(ObjectUtils.isNotEmpty(actions)) {
                for (int i = 0; i < actions.size(); i++) {
                    TpParaRelatedActionDto actionDto = actions.get(i);
                    if (ComputedFlagEnum.YES.getCode().equals(actionDto.getComputedFlag())) {
                        //替换逻辑判断符号 && ||
                        actionDto.setValue(
                                actionDto.getValue().replace(JEPLogicEnum.OR.getLogicValue(), JEPLogicEnum.OR.getLogicKey()));
                        actionDto.setValue(actionDto.getValue()
                                .replace(JEPLogicEnum.AND.getLogicValue(), JEPLogicEnum.AND.getLogicKey()));
                        //替换 方法
                        List<String> funcList = JEPUtils.getFuncShort(actionDto.getValue());
                        for (String func : funcList) {
                            String formula = actionDto.getValue();
                            formula = formula.replace(JEPSplitEnum.FUNC_SPLIT_FLAG.getFuncKey(), "");
                            func = func.replace(JEPSplitEnum.FUNC_SPLIT_FLAG.getFuncKey(), "");
                            JEPFuncEnum jEPFuncEnum = JEPFuncEnum.fromByKey(func);
                            formula = formula.replace(func, jEPFuncEnum.getFuncValue());
                            actionDto.setValue(formula);
                        }
                        //替换 参数
                        String formula = actionDto.getValue();
                        List<String> params = JEPUtils.getParam(formula);
                        for (String s : params) {
                            s = s.replace(JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey(), "");
                            if (codeToNameMap.containsKey(s)) {
                                formula = formula.replace(s, codeToNameMap.get(s))
                                        .replace(JEPSplitEnum.PARAM_SPLIT_FLAG.getFuncKey(), "");
                                actionDto.setValue(formula);
                            }
                        }
                    }
                    actionStr.append(actionDto.getParaName())
                            .append(" ")
                            .append(actionDto.getValue())
                            .append(" ")
                            .append(EditableEnum.ACTIVE.getCode().equals(actionDto.getEditable()) ?
                                    EditableEnum.ACTIVE.getValue() : EditableEnum.INACTIVE.getValue())
                            .append(" ");
                }
            }
            item.setActionStr(actionStr.toString());
        });
        rspData.setRows(res);
        return rspData;
    }

    @Override
    public TpParaRelatedCaseDto getInfoById(Long id) {
        TpParaRelatedCaseDto basicInfo = new TpParaRelatedCaseDto();

        TpParaRelatedCase tpParaRelatedCase = getById(id);
        if (Objects.isNull(tpParaRelatedCase)) {
            //数据已被删除
            throw new ServiceErrorException(MessageUtils.message("common.dataDeleted"));
        }
        BeanUtils.copyBeanProp(basicInfo, tpParaRelatedCase);
        //查找关联梯型
        List<TpCaseElevatorDto> elevatorList = iTpCaseElevatorService.initData(tpParaRelatedCase.getId());
        basicInfo.setRelationEnters(elevatorList);

        //条件list
        List<TpParaRelatedLogicDto> logicDtos = iTpParaRelatedLogicService.queryMoreInfo(
            Collections.singletonList(basicInfo.getId()));

        basicInfo.setLogicList(logicDtos);

        //结果list
        List<TpParaRelatedActionDto> actionDtos = iTpParaRelatedActionService.queryMoreInfo(
            Collections.singletonList(basicInfo.getId()));
        basicInfo.setActionList(actionDtos);
        return basicInfo;
    }

    @Override
    public int changeStatus(TpParaRelatedCaseDto param) {
        TpParaRelatedCase sqlData = getById(param.getId());
        if (sqlData == null) {
            //数据已被删除
            throw new ServiceErrorException(MessageUtils.message("common.dataDeleted"));
        }
        if (!ValidateUtils.allowUpdate(sqlData.getUpdateTime(), param.getUpdateTime())) {
            throw new ServiceErrorException(MessageUtils.message("common.dataUpdated"));
        }
        sqlData.setStatus(param.getStatus());
        sqlData.setUpdateBy(SecurityUtils.getStrUserId());
        sqlData.setUpdateTime(new Date());
        updateById(sqlData);
        return 1;
    }

    @Override
    public List<TpCaseElevatorDto> initData(Long caseId) {
        return iTpCaseElevatorService.initData(caseId);
    }

    @Override
    public List<Map<String, Object>> getInfoByTpElevatorModelId(Long tpElevatorModelId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //通过区域梯型id 在 tp_case_elevator 中查找 related_case
        List<TpCaseElevator> caseElevators = iTpCaseElevatorService.list(
            Wrappers.<TpCaseElevator>lambdaQuery()
                .eq(TpCaseElevator::getElevatorModelId, tpElevatorModelId)
                .eq(TpCaseElevator::getDelFlag, DelFlagEnum.NORMAL.getValue())
        );
        if (caseElevators == null || caseElevators.size() == 0) {
            //未查询到数据
            // throw new ServiceErrorException(MessageUtils.message("relatedCase.queryNoData"));
            return resultList;
        }
        List<Long> relatedCaseId = caseElevators.stream().map(TpCaseElevator::getRelatedCaseId).distinct()
            .collect(Collectors.toList());

        List<TpParaRelatedCase> tpParaRelatedCases = list(
            Wrappers.<TpParaRelatedCase>lambdaQuery()
                .in(TpParaRelatedCase::getId, relatedCaseId)
                .eq(TpParaRelatedCase::getDelFlag, DelFlagEnum.NORMAL.getValue())
        );
        if (tpParaRelatedCases == null || tpParaRelatedCases.size() == 0) {
            //未查询到数据
            throw new ServiceErrorException(MessageUtils.message("relatedCase.queryNoData"));
        }

        //logicList
        List<TpParaRelatedLogicDto> logicAllDtos = iTpParaRelatedLogicService
            .queryMoreInfo(relatedCaseId);
        //actionList
        List<TpParaRelatedActionDto> actionAllDtos = iTpParaRelatedActionService
            .queryMoreInfo(relatedCaseId);

        //根据 id 分组
        Map<Long, List<TpParaRelatedLogicDto>> relatedIdToLogic = logicAllDtos.stream()
            .collect(Collectors.groupingBy(TpParaRelatedLogicDto::getCaseId));

        Map<Long, List<TpParaRelatedActionDto>> relatedIdToAction = actionAllDtos.stream()
            .collect(Collectors.groupingBy(TpParaRelatedActionDto::getCaseId));

        for (TpParaRelatedCase tpParaRelatedCase : tpParaRelatedCases) {
            Map<String, Object> result = new HashMap<>();

            //逻辑关系
            result.put("relationship", tpParaRelatedCase.getRelationship());
            //infoList
            List<TpParaRelatedLogicInfo> infoList = new ArrayList<>();
            List<TpParaRelatedLogicDto> logicDtos = relatedIdToLogic
                .getOrDefault(tpParaRelatedCase.getId(), new ArrayList<>());
            List<TpParaRelatedActionDto> actionDtos = relatedIdToAction
                .getOrDefault(tpParaRelatedCase.getId(), new ArrayList<>());

            for (TpParaRelatedLogicDto logicDto : logicDtos) {
                TpParaRelatedLogicInfo logicInfo = new TpParaRelatedLogicInfo();
                logicInfo.setParaCode(logicDto.getParaCode());
                logicInfo.setParaName(logicDto.getParaName());
                logicInfo.setParaNameRU(logicDto.getParaNameRU());
                logicInfo.setParaNameES(logicDto.getParaNameES());
                logicInfo.setParaNameUS(logicDto.getParaNameUS());
                logicInfo.setValue(logicDto.getValue());
                OperationEnum operationEnum = OperationEnum.fromByValue(logicDto.getOperation());
                logicInfo.setOperation(operationEnum.getName());
                logicInfo.setInputType(logicDto.getInputType());
                infoList.add(logicInfo);
            }
            result.put("condition", infoList);
            result.put("conditionKeys",
                infoList.stream().map(TpParaRelatedLogicInfo::getParaCode).collect(Collectors.toList()));

            //actionInfos
            List<TpParaRelatedActionInfo> actionInfos = new ArrayList<>();

            for (TpParaRelatedActionDto actionDto : actionDtos) {
                TpParaRelatedActionInfo actionInfo = new TpParaRelatedActionInfo();
                actionInfo.setParaCode(actionDto.getParaCode());
                actionInfo.setParaName(actionDto.getParaName());
                actionInfo.setParaNameRU(actionDto.getParaNameRU());
                actionInfo.setParaNameES(actionDto.getParaNameES());
                actionInfo.setParaNameUS(actionDto.getParaNameUS());
                actionInfo.setValue(actionDto.getValue());
                actionInfo.setEditable(actionDto.getEditable());
                if (InputTypeEnum.SELECT.getCode().equals(actionDto.getInputType())) {
                    //封装可选options
                    List<String> selectItems = Arrays.asList(actionDto.getSelectItem().split(";"));
                    if (selectItems.size() > 0) {
                        List<Option> optionList = actionDto.getOptions().stream()
                            .filter(o -> selectItems.contains(o.getValue())).map(
                                item -> {
                                    Option option = new Option();
                                    option.setValue(item.getValue());
                                    option.setLabel(item.getLabel());
                                    option.setLabelRU(item.getLabelRU());
                                    option.setLabelES(item.getLabelES());
                                    option.setLabelUS(item.getLabelUS());
                                    return option;
                                }
                            ).collect(Collectors.toList());
                        actionInfo.setOptionList(optionList);
                    }
                }
                actionInfos.add(actionInfo);
            }
            result.put("result", actionInfos);
            resultList.add(result);
        }

        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteById(Long id, Date updateTime) {
        TpParaRelatedCase sqlData = getById(id);
        if (sqlData == null) {
            //数据已被删除
            throw new ServiceErrorException(MessageUtils.message("common.dataDeleted"));
        }
        if (!ValidateUtils.allowUpdate(sqlData.getUpdateTime(), updateTime)) {
            throw new ServiceErrorException(MessageUtils.message("common.dataUpdated"));
        }
        Date date = new Date();
        //删除关联表
        List<TpCaseElevator> caseElevators = iTpCaseElevatorService.list(
            Wrappers.<TpCaseElevator>lambdaQuery()
                .eq(TpCaseElevator::getRelatedCaseId, id)
                .eq(TpCaseElevator::getDelFlag, DelFlagEnum.NORMAL.getValue())
        );
        if (caseElevators != null && caseElevators.size() > 0) {
            caseElevators.forEach(item -> {
                item.setUpdateBy(SecurityUtils.getStrUserId());
                item.setUpdateTime(date);
                item.setDelFlag(DelFlagEnum.DELETED.getValue());
            });
            iTpCaseElevatorService.updateBatchById(caseElevators);
        }
        //删除条件表
        List<TpParaRelatedLogic> logicList = iTpParaRelatedLogicService.list(
            Wrappers.<TpParaRelatedLogic>lambdaQuery()
                .eq(TpParaRelatedLogic::getCaseId, id)
                .eq(TpParaRelatedLogic::getDelFlag, DelFlagEnum.NORMAL.getValue())
        );
        if (logicList != null && logicList.size() > 0) {
            logicList.forEach(item -> {
                item.setUpdateBy(SecurityUtils.getStrUserId());
                item.setUpdateTime(date);
                item.setDelFlag(DelFlagEnum.DELETED.getValue());
            });
            iTpParaRelatedLogicService.updateBatchById(logicList);
        }
        //删除结果表
        List<TpParaRelatedAction> resultList = iTpParaRelatedActionService.list(
            Wrappers.<TpParaRelatedAction>lambdaQuery()
                .eq(TpParaRelatedAction::getCaseId, id)
                .eq(TpParaRelatedAction::getDelFlag, DelFlagEnum.NORMAL.getValue())
        );
        if (resultList != null && resultList.size() > 0) {
            resultList.forEach(item -> {
                item.setUpdateBy(SecurityUtils.getStrUserId());
                item.setUpdateTime(date);
                item.setDelFlag(DelFlagEnum.DELETED.getValue());
            });
            iTpParaRelatedActionService.updateBatchById(resultList);
        }
        sqlData.setUpdateTime(date);
        sqlData.setUpdateBy(SecurityUtils.getStrUserId());
        sqlData.setDelFlag(DelFlagEnum.DELETED.getValue());
        updateById(sqlData);
        return 1;
    }

}
