package com.css.simulation.resource.server.app.service;

import api.common.pojo.common.ResponseBodyVO;
import api.common.pojo.param.scene.ScenePackageParam;
import api.common.pojo.param.scene.ScoringRulesParam;
import api.common.pojo.po.scene.*;
import api.common.pojo.vo.scene.ScenePackageNewVO;
import api.common.pojo.vo.scene.ScenePackageSublistVO;
import api.common.util.*;
import com.css.simulation.resource.server.infra.util.AuthUtil;
import com.css.simulation.resource.server.infra.db.mysql.mapper.*;
import com.css.simulation.resource.server.infra.util.SceneUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class ScenePackageService {

    @Resource
    private ScenePackageMapper scenePackageMapper;
    @Resource
    private ScenePackageSublistMapper scenePackageSublistMapper;
    @Resource
    private ParameterService parameterService;
    @Resource
    private ScoringRulesMapper scoringRulesMapper;
    @Resource
    private SceneNaturalMapper sceneNaturalMapper;
    @Resource
    private SceneAccidentMapper sceneAccidentMapper;
    @Resource
    private SceneStandardsRegulationsMapper sceneStandardsRegulationsMapper;
    @Resource
    private SceneGeneralTemplateMapper sceneGeneralTemplateMapper;
    @Resource
    private SceneUtil sceneUtil;


    /**
     * 测试包数据录入大保存：
     */
    @SneakyThrows
    public void saveScenePackage(ScenePackageSublistVO scenePackageSublistVO, Integer isLcw) {
        List<ScenePackageSublistVO> listSublistTree;
        ScenePackagePO po = new ScenePackagePO();
        po.setPackageName(scenePackageSublistVO.getSublistName());
        po.setCreateUserId(AuthUtil.getCurrentUserId());
        po.setShare("0");
        // 查询个人私有唯一
        ScenePackageNewVO scenePackageNewVO = scenePackageMapper.querySelfOnly(scenePackageSublistVO.getSublistName(), AuthUtil.getCurrentUserId());
        if (Objects.isNull(scenePackageNewVO)) {
            po.setWeight(scenePackageSublistVO.getWeight());
            po.setRemarks(scenePackageSublistVO.getRemarks());
            po.setSceneNum(scenePackageSublistVO.getSceneNum());
            po.setTreeNode(scenePackageSublistVO.getTreeNode());
            listSublistTree = scenePackageSublistVO.getChildren();
            po.setCreateTime(TimeUtil.getNowForMysql());
            po.setModifyTime(TimeUtil.getNowForMysql());
            po.setPackageCode(StringUtil.getRandomCode());
            String uuId = StringUtil.getRandomUUID();
            po.setPackageId(uuId);
            po.setIsDeleted("0");
            po.setCreateUserId(AuthUtil.getCurrentUserId());
            List<ScenePackageSublistPO> poList = new ArrayList<>();
            List<ScenePackageSublistPO> treeList;
            if (isLcw == 1) {
                treeList = instShareListTreeLCW(listSublistTree, uuId, uuId, poList, "0", 1);
            } else {
                treeList = instShareListTree(listSublistTree, uuId, uuId, poList, "0", 1);
            }
            //校验指标名称唯一
            if (treeList == null || treeList.size() < 1) {
                new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "指标数据为空，请检查。");
                return;
            }
            Set<String> set = new HashSet<>();
            Map<String, String> map = new HashMap<>();
            for (ScenePackageSublistPO vo : treeList) {
                Object sublistName = map.get(vo.getSublistName());
                if (ObjectUtil.isNull(sublistName)) {
                    map.put(vo.getSublistName(), vo.getSublistName());
                } else {
                    set.add(vo.getSublistName());
                }
            }
            if (ObjectUtil.isNotNull(set)) {
                new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "该条数据中指标名称 " + set + "重复，请检查。");
                return;
            }
            scenePackageMapper.saveScenePackage(po);
            scenePackageSublistMapper.saveScenePackageSublistAll(treeList);
            LogUtil.insert();
        } else {
            throw new RuntimeException("私有测试包 " + po.getPackageName() + " 已存在，请重新命名。");
        }

    }

    //查询测试包主表列表
    @SneakyThrows
    public List<ScenePackagePO> queryScenePackageList(ScenePackageParam params) {
        if (params != null && params.getShare() != null && params.getShare().equals("0")) {
            params.setCreateUserId(AuthUtil.getCurrentUserId());
        }
        return scenePackageMapper.queryScenePackageList(params);
    }

    //修改主表数据
    @SneakyThrows
    public ResponseBodyVO<String> updateScenePackage(List<ScenePackageSublistVO> params) {
        List<ScenePackageSublistVO> listSublictTree = new ArrayList<>();
        ScenePackagePO po = new ScenePackagePO();
        for (ScenePackageSublistVO vo : params) {
            //判断唯一
            po.setPackageName(vo.getSublistName());
            po.setCreateUserId(AuthUtil.getCurrentUserId());
            if (ObjectUtil.isNull(vo.getShare())) {
                po.setShare("0");
            } else {
                po.setShare(vo.getShare());
            }
            String share = po.getShare();
            ScenePackageNewVO scenePackageNewVO;
            po.setPackageId(vo.getId());
            if ("0".equals(share)) {
                po.setCreateUserId(AuthUtil.getCurrentUserId());
            }
            scenePackageNewVO = scenePackageMapper.queryByPackageName(po);
            if (ObjectUtil.isNotNull(scenePackageNewVO)) {
                return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "测试包名称:" + po.getPackageName() + "已存在，请重新命名");
            }
            po.setWeight(vo.getWeight());
            po.setRemarks(vo.getRemarks());
            po.setSceneNum(vo.getSceneNum());
            po.setTreeNode(vo.getTreeNode());
            listSublictTree = vo.getChildren();
        }

        po.setModifyTime(TimeUtil.getNowForMysql());
        po.setModifyUserId(AuthUtil.getCurrentUserId());
        po.setIsDeleted("0");
        if (ObjectUtil.isNull(po.getShare())) {
            po.setShare("0");
        }
        List<ScenePackageSublistPO> poList = new ArrayList<>();
        List<ScenePackageSublistPO> treeList = instShareListTree(listSublictTree, po.getPackageId(), po.getPackageId(), poList, "0", 1);
        if (treeList == null || treeList.size() < 1) {
            return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "指标数据为空，请检查");
        }
        Set<String> set = new HashSet<>();
        Map<String, String> map = new HashMap<>();
        for (ScenePackageSublistPO vo : treeList) {
            Object sublistName = map.get(vo.getSublistName());
            if (ObjectUtil.isNull(sublistName)) {
                map.put(vo.getSublistName(), vo.getSublistName());
            } else {
                set.add(vo.getSublistName());
            }
        }
        if (ObjectUtil.isNotNull(set)) {
            return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "该条数据中指标名称:" + set + "重复，请检查");
        }
        po.setIsUnavailable("0");
        scenePackageMapper.updateScenePackage(po);
        scenePackageSublistMapper.deleteScenePackageSublist(po.getPackageId());
        scenePackageSublistMapper.saveScenePackageSublistAll(treeList);
        LogUtil.update();
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS);
    }

    //删除测试包
    @SneakyThrows
    public void deleteList(ScenePackageParam params) {
        ScenePackagePO po = new ScenePackagePO();
        po.setModifyUserId(AuthUtil.getCurrentUserId());
        po.setModifyTime(TimeUtil.getNowForMysql());
        po.setIsDeleted("1");
        po.setPackageId(params.getPackageId());
        scenePackageSublistMapper.deleteScenePackageSublist(params.getPackageId());
        scenePackageMapper.deleteScenePackage(po);
        LogUtil.delete();
    }


    /**
     * 查询场景测试包详情
     */
    @SneakyThrows
    public List<ScenePackageSublistVO> queryScenePackageSublistList(ScenePackageParam params) {
        ScenePackageNewVO vo = scenePackageMapper.queryScenePackageBySublist(params.getPackageId());
        ScenePackageSublistPO po = new ScenePackageSublistPO();
        po.setRootId(params.getPackageId());
        List<ScenePackageSublistVO> scenePackageSublistVOS = scenePackageSublistMapper.queryScenePackageSublistList(po);
        //构建根节点
        ScenePackageSublistVO root = new ScenePackageSublistVO();
        root.setId(vo.getPackageId());
        root.setParentId("0");
        root.setSublistName(vo.getPackageName());
        root.setWeight(vo.getWeight());
        root.setSceneNum(vo.getSceneNum());
        root.setRemarks(vo.getRemarks());
        root.setTreeNode(vo.getTreeNode());
        scenePackageSublistVOS.add(0, root);

        scenePackageSublistVOS.forEach(ScenePackageSublistVO -> {
            if (ObjectUtil.isNotNull(ScenePackageSublistVO.getRuleNameArray())) {
                ScenePackageSublistVO.setRuleNameArrayS(ScenePackageSublistVO.getRuleNameArray().split(","));
            }
        });
        //list转tree
        return listToTree(scenePackageSublistVOS);
    }

    /**
     * list转tree
     */
    public static List<ScenePackageSublistVO> listToTree(List<ScenePackageSublistVO> list) {
        List<ScenePackageSublistVO> treeList = new ArrayList<>();
        for (ScenePackageSublistVO vo : list) {
            if ("0".equals(vo.getParentId())) {
                treeList.add(findChildren(vo, list));
            }
        }
        return treeList;
    }

    /**
     * list转tree 递归
     */
    private static ScenePackageSublistVO findChildren(ScenePackageSublistVO vo, List<ScenePackageSublistVO> list) {
        for (ScenePackageSublistVO node : list) {
            if (vo.getId().equals(node.getParentId())) {
                if (vo.getChildren() == null || vo.getChildren().size() == 0) {
                    vo.setChildren(new ArrayList<>());
                }
                vo.getChildren().add(findChildren(node, list));
            }
        }
        return vo;
    }

    /**
     * 级联获取场景指标
     *
     * @param parentVoList   首次传null
     * @param isRoot         首次传true
     * @param scenePackageId 场景包id
     */
    public List<ScenePackageSublistVO> selectScenePackageSubListTree(List<ScenePackageSublistVO> parentVoList,
                                                                     boolean isRoot, String scenePackageId) {
        ScenePackageSublistPO params = new ScenePackageSublistPO();
        params.setParentId(scenePackageId);
        if (isRoot) {
            //查找一级节点
            parentVoList = scenePackageSublistMapper.queryScenePackageSublistList(params);
            if (parentVoList != null && parentVoList.size() > 0) {
                selectScenePackageSubListTree(parentVoList, false, null);
            }
        } else {
            //获取子节点集合
            for (ScenePackageSublistVO pvo : parentVoList) {
                params.setParentId(pvo.getId());
                List<ScenePackageSublistVO> cvoList = scenePackageSublistMapper.queryScenePackageSublistList(params);
                if (cvoList != null && cvoList.size() > 0) {
                    //存入父节点集合中
                    pvo.setChildren(cvoList);
                    //  pvo.setHasChildren(true);
                    //继续查找下一节点
                    selectScenePackageSubListTree(cvoList, false, null);
                }
            }
        }
        return parentVoList;
    }


    //分享
    @SneakyThrows
    public ResponseBodyVO<String> instShareList(ScenePackageParam params) {
        //查询测试包主表
        ScenePackagePO scenePackagePO = scenePackageMapper.queryScenePackage(params);
        ScenePackagePO po = new ScenePackagePO();
        po.setShare("1");
        po.setPackageName(scenePackagePO.getPackageName());
        ScenePackageNewVO scenePackageNewVO = scenePackageMapper.queryByPackageName(po);

        BeanUtils.copyProperties(scenePackagePO, po);
        po.setCreateTime(TimeUtil.getNowForMysql());
        po.setModifyTime(TimeUtil.getNowForMysql());
        po.setCreateUserId(AuthUtil.getCurrentUserId());
        po.setPackageCode(StringUtil.getRandomCode());
        String uuId;
        if (ObjectUtil.isNotNull(scenePackageNewVO)) {
            uuId = scenePackageNewVO.getPackageId();
        } else {
            uuId = StringUtil.getRandomUUID();
        }
        po.setPackageId(uuId);
        po.setIsDeleted("0");
        po.setShare("1");
        List<ScenePackageSublistPO> poList = new ArrayList<>();
        List<ScenePackageSublistVO> listSublist = selectScenePackageSubListTree(null, true, params.getPackageId());
        List<ScenePackageSublistPO> treeList = instShareListTreeFX(listSublist, uuId, uuId, poList, "1", 1);
        log.info("指标树为：" + treeList);
        if (CollectionUtil.isNotEmpty(treeList)) {
            Set<String> set = new HashSet<>();
            Map<String, String> map = new HashMap<>();
            //打分规则
            ScoringRulesParam scoringRulesParam = new ScoringRulesParam();
            ScoringRulesParam gyParam = new ScoringRulesParam();
            for (ScenePackageSublistPO vo : treeList) {
                Object sublistName = map.get(vo.getSublistName());
                if (ObjectUtil.isNull(sublistName)) {
                    map.put(vo.getSublistName(), vo.getSublistName());
                } else {
                    set.add(vo.getSublistName());
                }
                if (StringUtil.isNotEmpty(vo.getPackageAndRules())) {
                    // 分享打分规则
                    scoringRulesParam.setRulesId(vo.getPackageAndRules());
                    ScoringRulesPO syPo = scoringRulesMapper.queryScoringRules(scoringRulesParam);  // 私有
                    log.info("打分规则为：" + syPo);
                    if (syPo == null) {
                        throw new RuntimeException("该场景包关联的打分规则已被删除，分享失败。");
                    }
                    gyParam.setShare("1");
                    gyParam.setRuleName(syPo.getRuleName());
                    ScoringRulesPO gyPo = scoringRulesMapper.queryScoringRulesByRuleName(gyParam);
                    if (ObjectUtil.isNotNull(gyPo)) {
                        syPo.setRulesId(gyPo.getRulesId());
                        syPo.setShare("1");
                        syPo.setModifyTime(TimeUtil.getNowForMysql());
                        syPo.setModifyUserId(AuthUtil.getCurrentUserId());
                        scoringRulesMapper.updateScoringRules(syPo);
                    } else {
                        syPo.setCreateTime(TimeUtil.getNowForMysql());
                        syPo.setModifyTime(TimeUtil.getNowForMysql());
                        syPo.setRulesId(StringUtil.getRandomUUID());
                        syPo.setRulesCode(StringUtil.getRandomCode());
                        syPo.setCreateUserId(AuthUtil.getCurrentUserId());
                        syPo.setIsDeleted("0");
                        syPo.setShare("1");
                        scoringRulesMapper.saveScoringRules(syPo);
                    }
                    vo.setPackageAndRules(syPo.getRulesId());
                }

                //分享场景
                //自然场景
                String sceneNaturalIds = vo.getSceneNaturalIds();
                if (ObjectUtil.isNotNull(sceneNaturalIds)) {
                    String sceneNaturalIdsGy = "";
                    List<String> sceneNaturalIdList = Arrays.asList(sceneNaturalIds.split(","));
                    SceneNaturalPO SceneNaturalparm = new SceneNaturalPO();
                    SceneNaturalparm.setShare("1");
                    for (String naturalId : sceneNaturalIdList) {
                        SceneNaturalPO SceneNaturalPOSy = sceneNaturalMapper.querySceneNaturalById(naturalId);
                        SceneNaturalparm.setNaturalName(SceneNaturalPOSy.getNaturalName());
                        SceneNaturalPO sceneNaturalPOByName = sceneNaturalMapper.querySceneNaturaByName(SceneNaturalparm);
                        SceneNaturalPOSy.setShare("1");
                        //是否已存在
                        if (ObjectUtil.isNotNull(sceneNaturalPOByName)) {
                          /* if(!sceneNaturalPOByName.getShare().equals("1")){

                           }*/
                            SceneNaturalPOSy.setNaturalId(sceneNaturalPOByName.getNaturalId());
                            SceneNaturalPOSy.setModifyTime(TimeUtil.getNowForMysql());
                            SceneNaturalPOSy.setModifyUserId(AuthUtil.getCurrentUserId());
                            sceneNaturalMapper.updateSceneNatural(SceneNaturalPOSy);
                        } else {
                            SceneNaturalPOSy.setNaturalId(StringUtil.getRandomUUID());
                            SceneNaturalPOSy.setCreateTime(TimeUtil.getNowForMysql());
                            SceneNaturalPOSy.setCreateUserId(AuthUtil.getCurrentUserId());
                            SceneNaturalPOSy.setModifyTime(TimeUtil.getNowForMysql());
                            SceneNaturalPOSy.setModifyUserId("");
                            sceneNaturalMapper.saveSceneNatural(SceneNaturalPOSy);
                        }
                        if (ObjectUtil.isNull(sceneNaturalIdsGy)) {
                            sceneNaturalIdsGy = SceneNaturalPOSy.getNaturalId();
                        } else {
                            sceneNaturalIdsGy = sceneNaturalIdsGy + "," + SceneNaturalPOSy.getNaturalId();
                        }
                    }
                    vo.setSceneNaturalIds(sceneNaturalIdsGy);
                }

                //标准法规
                String sceneStatueIds = vo.getSceneStatueIds();
                if (ObjectUtil.isNotNull(sceneStatueIds)) {
                    String sceneStatueIdsGy = "";
                    List<String> sceneStatueIdList = Arrays.asList(sceneStatueIds.split(","));
                    StandardsRegulationsPO standardsRegulationsPO = new StandardsRegulationsPO();
                    standardsRegulationsPO.setShare("1");
                    for (String sceneStatueId : sceneStatueIdList) {
                        StandardsRegulationsPO standardsRegulationsPOSy = sceneStandardsRegulationsMapper.queryStandardsRegulationsById(sceneStatueId);
                        standardsRegulationsPO.setSceneName(standardsRegulationsPOSy.getSceneName());
                        StandardsRegulationsPO StandardsRegulationsByName = sceneStandardsRegulationsMapper.queryStandardsRegulationsByName(standardsRegulationsPO);
                        standardsRegulationsPOSy.setShare("1");
                        //是否已存在
                        if (ObjectUtil.isNotNull(StandardsRegulationsByName)) {
                          /* if(!sceneNaturalPOByName.getShare().equals("1")){

                           }*/
                            standardsRegulationsPOSy.setRegulationsId(StandardsRegulationsByName.getRegulationsId());
                            standardsRegulationsPOSy.setModifyTime(TimeUtil.getNowForMysql());
                            standardsRegulationsPOSy.setModifyUserId(AuthUtil.getCurrentUserId());
                            sceneStandardsRegulationsMapper.updateStandardsRegulations(standardsRegulationsPOSy);
                        } else {
                            standardsRegulationsPOSy.setRegulationsId(StringUtil.getRandomUUID());
                            standardsRegulationsPOSy.setCreateTime(TimeUtil.getNowForMysql());
                            standardsRegulationsPOSy.setCreateUserId(AuthUtil.getCurrentUserId());
                            standardsRegulationsPOSy.setModifyTime(TimeUtil.getNowForMysql());
                            standardsRegulationsPOSy.setModifyUserId("");
                            sceneStandardsRegulationsMapper.saveStandardsRegulations(standardsRegulationsPOSy);
                        }

                        if (ObjectUtil.isNull(sceneStatueIdsGy)) {
                            sceneStatueIdsGy = standardsRegulationsPOSy.getRegulationsId();
                        } else {
                            sceneStatueIdsGy = sceneStatueIdsGy + "," + standardsRegulationsPOSy.getRegulationsId();
                        }
                    }
                    vo.setSceneStatueIds(sceneStatueIdsGy);
                }

                //交通事故
                String sceneTrafficIds = vo.getSceneTrafficIds();
                if (ObjectUtil.isNotNull(sceneTrafficIds)) {
                    String sceneTrafficIdsGy = "";
                    List<String> sceneTrafficIdList = Arrays.asList(sceneTrafficIds.split(","));
                    SceneAccidentPO sceneAccidentPO = new SceneAccidentPO();
                    sceneAccidentPO.setShare("1");
                    for (String sceneStatueId : sceneTrafficIdList) {
                        SceneAccidentPO sceneAccidentPOSy = sceneAccidentMapper.querySceneAccidentById(sceneStatueId);
                        sceneAccidentPO.setSceneName(sceneAccidentPOSy.getSceneName());
                        SceneAccidentPO sceneAccidentPOByName = sceneAccidentMapper.querySceneAccidentByNmae(sceneAccidentPO);
                        sceneAccidentPOSy.setShare("1");
                        //是否已存在
                        if (ObjectUtil.isNotNull(sceneAccidentPOByName)) {
                          /* if(!sceneNaturalPOByName.getShare().equals("1")){

                           }*/
                            sceneAccidentPOSy.setAccidentId(sceneAccidentPOByName.getAccidentId());
                            sceneAccidentPOSy.setModifyTime(TimeUtil.getNowForMysql());
                            sceneAccidentPOSy.setModifyUserId(AuthUtil.getCurrentUserId());
                            sceneAccidentMapper.updateSceneAccident(sceneAccidentPOSy);
                        } else {
                            sceneAccidentPOSy.setAccidentId(StringUtil.getRandomUUID());
                            sceneAccidentPOSy.setCreateTime(TimeUtil.getNowForMysql());
                            sceneAccidentPOSy.setCreateUserId(AuthUtil.getCurrentUserId());
                            sceneAccidentPOSy.setModifyTime(TimeUtil.getNowForMysql());
                            sceneAccidentPOSy.setModifyUserId("");
                            sceneAccidentMapper.saveSceneAccident(sceneAccidentPOSy);
                        }
                        if (ObjectUtil.isNull(sceneTrafficIdsGy)) {
                            sceneTrafficIdsGy = sceneAccidentPOSy.getAccidentId();
                        } else {
                            sceneTrafficIdsGy = sceneTrafficIdsGy + "," + sceneAccidentPOSy.getAccidentId();
                        }
                    }
                    vo.setSceneTrafficIds(sceneTrafficIdsGy);
                }

                //泛化模板
               /* String sceneGeneralizationIds=vo.getSceneGeneralizationIds();
                if(ObjectUtil.isNotNull(sceneGeneralizationIds)){
                    List<String> sceneGeneralizationIdList=Arrays.asList(sceneGeneralizationIds.split(","));
                    SceneGeneralTemplatePO sceneGeneralTemplatePO=new SceneGeneralTemplatePO();
                    sceneGeneralTemplatePO.setShare("1");
                    for (String sceneStatueId: sceneGeneralizationIdList) {
                        SceneGeneralTemplatePO sceneGeneralTemplatePOSy = sceneGeneralTemplateMapper.querySceneGeneralTemplateById(sceneStatueId);
                        sceneGeneralTemplatePO.setSceneId(sceneGeneralTemplatePOSy.getSceneId());
                        SceneGeneralTemplatePO sceneGeneralTemplatePOByName=  sceneGeneralTemplateMapper.querySceneGeneralTemplateByName(sceneGeneralTemplatePO);
                        sceneGeneralTemplatePOSy.setShare("1");
                        //是否已存在
                        if(ObjectUtil.isNotNull(sceneGeneralTemplatePOByName)){
                          *//* if(!sceneNaturalPOByName.getShare().equals("1")){

                           }*//*
                            sceneGeneralTemplatePOSy.setId(sceneGeneralTemplatePOByName.getId());
                            sceneGeneralTemplatePOSy.setModifyTime(TimeUtil.getNowForMysql());
                            sceneGeneralTemplatePOSy.setModifyUserId(AuthUtil.getCurrentUserId());
                            sceneGeneralTemplateMapper.updateSceneGeneralTemplate(sceneGeneralTemplatePOSy);
                        }else{
                            sceneGeneralTemplatePOSy.setId(StringUtil.getRandomUUID());
                            sceneGeneralTemplatePOSy.setCreateTime(TimeUtil.getNowForMysql());
                            sceneGeneralTemplatePOSy.setCreateUserId(AuthUtil.getCurrentUserId());
                            sceneGeneralTemplatePOSy.setModifyTime(TimeUtil.getNowForMysql());
                            sceneGeneralTemplatePOSy.setModifyUserId("");
                            sceneGeneralTemplateMapper.saveSceneGeneralTemplate(sceneGeneralTemplatePOSy);
                        }
                    }
                };*/
                //泛化
                String templateId = vo.getTemplateId();
                if (ObjectUtil.isNotNull(templateId)) {
                    SceneGeneralTemplatePO sceneGeneralTemplatePO = new SceneGeneralTemplatePO();
                    sceneGeneralTemplatePO.setShare("1");
                    SceneGeneralTemplatePO sceneGeneralTemplatePOSy = sceneGeneralTemplateMapper.querySceneGeneralTemplateById(templateId);
                    sceneGeneralTemplatePO.setSceneId(sceneGeneralTemplatePOSy.getSceneId());
                    SceneGeneralTemplatePO sceneGeneralTemplatePOByName = sceneGeneralTemplateMapper.querySceneGeneralTemplateByName(sceneGeneralTemplatePO);
                    sceneGeneralTemplatePOSy.setShare("1");
                    //是否已存在
                    if (ObjectUtil.isNotNull(sceneGeneralTemplatePOByName)) {
                        sceneGeneralTemplatePOSy.setId(sceneGeneralTemplatePOByName.getId());
                        sceneGeneralTemplatePOSy.setModifyTime(TimeUtil.getNowForMysql());
                        sceneGeneralTemplatePOSy.setModifyUserId(AuthUtil.getCurrentUserId());
                        sceneGeneralTemplateMapper.updateSceneGeneralTemplate(sceneGeneralTemplatePOSy);
                    } else {
                        String uuFhId = StringUtil.getRandomUUID();
                        sceneGeneralTemplatePOSy.setId(uuFhId);
                        sceneGeneralTemplatePOSy.setCreateTime(TimeUtil.getNowForMysql());
                        sceneGeneralTemplatePOSy.setCreateUserId(AuthUtil.getCurrentUserId());
                        sceneGeneralTemplatePOSy.setModifyTime(TimeUtil.getNowForMysql());
                        sceneGeneralTemplatePOSy.setModifyUserId("");
                        sceneGeneralTemplateMapper.saveSceneGeneralTemplate(sceneGeneralTemplatePOSy);
                        vo.setTemplateId(uuFhId);
                    }
                }

            }
            if (ObjectUtil.isNotNull(set)) {
                return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "该条数据中指标名称:" + set + "重复，请检查");
            }


        }
        //判断是否存在，存在覆盖
        if (ObjectUtil.isNotNull(scenePackageNewVO)) {
            //return new ResponseBodyVO<>(ResponseBodyVO.Response.CLIENT_FAILURE, "测试包名称:" + listName.get(0).getPackageName() + "的测试包已存在，请检查");
            scenePackagePO.setShare("1");
            scenePackagePO.setModifyTime(TimeUtil.getNowForMysql());
            scenePackagePO.setModifyUserId(AuthUtil.getCurrentUserId());
            scenePackagePO.setPackageId(scenePackageNewVO.getPackageId());
            scenePackageMapper.updateScenePackage(scenePackagePO);
            scenePackageSublistMapper.deleteScenePackageSublist(scenePackageNewVO.getPackageId());
        } else {
            scenePackageMapper.saveScenePackage(po);
        }
        scenePackageSublistMapper.saveScenePackageSublistAll(treeList);
        LogUtil.insert();
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS);
    }

    /**
     * 根据级联结果转化为单级list
     *
     * @param parentVoList   首次传null
     * @param scenePackageId 场景包id
     * @return
     */
    public List<ScenePackageSublistPO> instShareListTree(List<ScenePackageSublistVO> parentVoList,
                                                         String scenePackageId, String rootId, List<ScenePackageSublistPO> poList
            , String share, Integer level) {
        //获取子节点集合
        for (int i = 0; i < parentVoList.size(); i++) {
            ScenePackageSublistPO params = new ScenePackageSublistPO();
            BeanUtils.copyProperties(parentVoList.get(i), params);
            params.setParentId(scenePackageId);
            params.setRootId(rootId);
            params.setSublistName(parentVoList.get(i).getSublistName());
            params.setCreateTime(TimeUtil.getNowForMysql());
            params.setModifyTime(TimeUtil.getNowForMysql());
            params.setCreateUserId(AuthUtil.getCurrentUserId());
            //添加泛化后处理  如果是泛化用返回值中的结果
            if (ObjectUtil.isNull(parentVoList.get(i).getSceneGeneralizationIds())) {
                String uuId = StringUtil.getRandomUUID();
                params.setId(uuId);   //主键ID
            } else if (ObjectUtil.isNotNull(parentVoList.get(i).getSceneGeneralizationIds())) {
                scenePackageSublistMapper.deleteScenePackageSublistById(parentVoList.get(i).getId());
            }
            params.setIsDeleted("0");
            params.setShare(share);
            params.setPackageLevel(level);
            params.setTreeNode(parentVoList.get(i).getTreeNode());
            if (ObjectUtil.isNotNull(parentVoList.get(i).getRuleNameArrayS())) {
                params.setRuleNameArray(StringUtils.join(Arrays.asList(parentVoList.get(i).getRuleNameArrayS()), ','));
            }
            List<ScenePackageSublistVO> cvoList = parentVoList.get(i).getChildren();
            poList.add(params);
            if (cvoList != null && cvoList.size() > 0) {
                //继续查找下一节点
                int b = level + 1;
                instShareListTree(cvoList, params.getId(), rootId, poList, share, b);
            }
            parentVoList.remove(parentVoList.get(i));
            i--;

        }


        return poList;
    }

    //测试包名查唯一
    public ScenePackageNewVO queryByPackageName(ScenePackagePO params) {
        return scenePackageMapper.queryByPackageName(params);
    }

    //查询个人测试包数量
    @SneakyThrows
    public Map<String, Integer> queryPackageCount() {
        ScenePackagePO params = new ScenePackagePO();
        params.setCreateUserId(AuthUtil.getCurrentUserId());
        params.setShare("0");
        int myPackageCount = scenePackageMapper.queryPackageCount(params);
        HashMap<String, Integer> sceneParam = parameterService.getSceneParam();
        sceneParam.put("myPackageCount", myPackageCount);//场景包数量
        return sceneParam;
    }


    public List<ScenePackageSublistPO> instShareListTreeFX(List<ScenePackageSublistVO> parentVoList,
                                                           String scenePackageId, String rootId, List<ScenePackageSublistPO> poList
            , String share, Integer level) {
        //获取子节点集合
        for (int i = 0; i < parentVoList.size(); i++) {
            ScenePackageSublistPO params = new ScenePackageSublistPO();
            BeanUtils.copyProperties(parentVoList.get(i), params);
            params.setParentId(scenePackageId);
            params.setRootId(rootId);
            params.setSublistName(parentVoList.get(i).getSublistName());
            params.setCreateTime(TimeUtil.getNowForMysql());
            params.setModifyTime(TimeUtil.getNowForMysql());
            params.setCreateUserId(AuthUtil.getCurrentUserId());
            //添加泛化后处理  如果是泛化用返回值中的结果
            if (ObjectUtil.isNull(parentVoList.get(i).getSceneGeneralizationIds())) {
                String uuId = StringUtil.getRandomUUID();
                params.setId(uuId);   //主键ID
            } else if (ObjectUtil.isNotNull(parentVoList.get(i).getSceneGeneralizationIds())) {
                if (share.equals("1")) {
                    String uuId = StringUtil.getRandomUUID();
                    params.setId(uuId);
                } else {
                    scenePackageSublistMapper.deleteScenePackageSublistById(parentVoList.get(i).getId());
                }
            }
            params.setIsDeleted("0");
            params.setShare(share);
            params.setPackageLevel(level);
            params.setTreeNode(parentVoList.get(i).getTreeNode());
            List<ScenePackageSublistVO> cvoList = parentVoList.get(i).getChildren();
            poList.add(params);
            if (cvoList != null && cvoList.size() > 0) {
                //继续查找下一节点
                int b = level + 1;
                instShareListTreeFX(cvoList, params.getId(), rootId, poList, share, b);
            }
            parentVoList.remove(parentVoList.get(i));
            i--;
        }
        return poList;
    }

    public List<ScenePackageSublistPO> instShareListTreeLCW(List<ScenePackageSublistVO> parentVoList,
                                                            String scenePackageId, String rootId, List<ScenePackageSublistPO> poList
            , String share, Integer level) {
        //获取子节点集合
        for (int i = 0; i < parentVoList.size(); i++) {
            ScenePackageSublistPO params = new ScenePackageSublistPO();
            BeanUtils.copyProperties(parentVoList.get(i), params);
            params.setParentId(scenePackageId);
            params.setRootId(rootId);
            params.setSublistName(parentVoList.get(i).getSublistName());
            params.setCreateTime(TimeUtil.getNowForMysql());
            params.setModifyTime(TimeUtil.getNowForMysql());
            params.setCreateUserId(AuthUtil.getCurrentUserId());
            //添加泛化后处理  如果是泛化用返回值中的结果
            String uuId = StringUtil.getRandomUUID();
            params.setId(uuId);   //主键ID
            params.setIsDeleted("0");
            params.setShare(share);
            params.setPackageLevel(level);
            params.setTreeNode(parentVoList.get(i).getTreeNode());
            if (ObjectUtil.isNotNull(parentVoList.get(i).getRuleNameArrayS())) {
                params.setRuleNameArray(StringUtils.join(Arrays.asList(parentVoList.get(i).getRuleNameArrayS()), ','));
            }
            List<ScenePackageSublistVO> cvoList = parentVoList.get(i).getChildren();
            poList.add(params);
            if (cvoList != null && cvoList.size() > 0) {
                //继续查找下一节点
                int b = level + 1;
                instShareListTreeLCW(cvoList, params.getId(), rootId, poList, share, b);
            }
            parentVoList.remove(parentVoList.get(i));
            i--;
        }
        return poList;
    }

}
