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

import api.common.pojo.common.ResponseBodyVO;
import api.common.pojo.constants.DictConstants;
import api.common.pojo.constants.LogConstants;
import api.common.pojo.param.MinioParameter;
import api.common.pojo.param.scene.*;
import api.common.pojo.po.scene.*;
import api.common.pojo.po.system.SceneImportPO;
import api.common.util.*;
import com.alibaba.druid.util.StringUtils;
import com.css.simulation.resource.server.infra.util.AuthUtil;
import com.css.simulation.resource.server.infra.feign.service.FileDownService;
import com.css.simulation.resource.server.infra.db.mysql.mapper.SceneAccidentMapper;
import com.css.simulation.resource.server.infra.db.mysql.mapper.ScenePackageMapper;
import com.css.simulation.resource.server.infra.db.mysql.mapper.ScenePackageSublistMapper;
import com.css.simulation.resource.server.infra.db.mysql.mapper.SystemScenePackageSublistMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SceneAccidentService {

    @Resource
    private SceneAccidentMapper sceneAccidentMapper;
    @Resource
    private ScenePackageSublistMapper scenePackageSublistMapper;
    @Resource
    private ScenePackageMapper scenePackageMapper;
    @Resource
    private SystemScenePackageSublistMapper systemScenePackageSublistMapper;
    @Resource
    private FileDownService fileDownService;
    @Resource
    private LogService logService;

    @Resource
    private SceneEvaluationRuleService sceneEvaluationRuleService;

    /**
     * 获取交通事故场景数据：
     */
    @SneakyThrows
    public ResponseBodyVO<String> importJtSg(SceneAccidentParam param) {

        MinioParameter MI = new MinioParameter();
        MI.setObjectName(param.getJsonAddress());
        Response download = fileDownService.download(MI);
        // -------------------------------- label.json --------------------------------
        String json = download.body().toString();
       /* byte[] bytes=json.getBytes("UTF-8");
        json=new String(bytes,3,bytes.length-3);*/
        ObjectMapper objMap = new ObjectMapper();
        JsonNode root = objMap.readTree(json);
        //判断场景名称唯一
        String sceneName = root.path("场景名称").asText();
        SceneAccidentPO sceneAccidentPO = new SceneAccidentPO();
        sceneAccidentPO.setShare("0");
        sceneAccidentPO.setSceneName(sceneName);
        SceneAccidentPO sceneAccidentPOByName = sceneAccidentMapper.querySceneAccidentByNmae(sceneAccidentPO);

        sceneAccidentPO = sceneAccidentPO.builder()
                .accidentId(StringUtil.getRandomUUID())
                .sceneName(sceneName)
                .scenceResume(root.path("场景描述").asText())
                .selfDriving(root.path("自车驾驶行为").asText())
                .targetDriving(root.path("目标驾驶行为").asText())
                .selfReaction(root.path("自车反应行为").asText())
                .conflictBehavior(root.path("冲突行为").asText())
                .conflictType(root.path("冲突类型").asText())
                .sceneTime(root.path("时间").asText())
                .sceneWeather(root.path("天气").asText())
                .maxTime(root.path("max_time").asText())
                .isDeleted("0")
                .build();
        if (null != param.getJsonAddress() && !param.getJsonAddress().equals("")) {
            sceneAccidentPO.setJsonAddress(param.getJsonAddress());
        }
        if (null != param.getXmlAddress() && !param.getXmlAddress().equals("")) {
            sceneAccidentPO.setXmlAddress(param.getXmlAddress());
        }
        if (null != param.getXodrAddress() && !param.getXodrAddress().equals("")) {
            sceneAccidentPO.setXodrAddress(param.getXodrAddress());
        }
        if (null != param.getOsgbAddress() && !param.getOsgbAddress().equals("")) {
            sceneAccidentPO.setOsgbAddress(param.getOsgbAddress());
        }
        if (null != param.getVideoAddress() && !param.getVideoAddress().equals("")) {
            sceneAccidentPO.setVideoAddress(param.getVideoAddress());
        }
        if (ObjectUtil.isNull(sceneAccidentPOByName)) {
            // -------------------------------- 保存数据到 mysql --------------------------------
            sceneAccidentPO.setCreateTime(TimeUtil.getNowForMysql());
            sceneAccidentPO.setCreateUserId(AuthUtil.getCurrentUserId());
            sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());


         /*   if (null != param.getVideoPreview() && !param.getVideoPreview().equals("")) {
                sceneAccidentPO.setVideoPreview(param.getVideoPreview());
            }*/
            sceneAccidentMapper.saveSceneAccident(sceneAccidentPO);
        } else {
            // -------------------------------- 修改数据到 mysql --------------------------------
            sceneAccidentPO.setAccidentId(sceneAccidentPOByName.getAccidentId());
            sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());
            sceneAccidentPO.setModifyUserId(AuthUtil.getCurrentUserId());
            sceneAccidentMapper.updateSceneAccident(sceneAccidentPO);
        }
        return new ResponseBodyVO(ResponseBodyVO.Response.SUCCESS);

    }

    /*  */

    /**
     * 获取交通事故场景数据：
     *//*
    @SneakyThrows
    public void testCS(SceneAccidentParam param) {
        //1 获取所有目录下所有场景
        String dataUrl0 = "C:\\Users\\CSS\\Desktop\\GQ\\仿真云平台\\测试场景样例数据\\交通事故场景\\China_Expressway_002";     // 场景数据根路径
        //  System.out.println("--------"+param.getPath());
        File[] scenes = FileUtil.getDirectory(dataUrl0).listFiles();
        if (scenes == null) {
            throw new RuntimeException("目录：" + dataUrl0 + " 下没有文件！");
        }

        String fileName = null;
        try {
            SceneAccidentPO sceneAccidentPO = null;
            for (File scene : scenes) {
                String dataUrl = scene.getAbsolutePath();
                if (dataUrl.indexOf(".json") != -1) {
                    //获取文件名
                    File tempFile = new File(dataUrl.trim());
                    fileName = tempFile.getName();
                    fileName = fileName.substring(0, fileName.lastIndexOf("."));
                    // -------------------------------- 读取结构化数据文件 --------------------------------
                    List<String> exceptionList = new ArrayList<>();     // 异常列表
                    // -------------------------------- label.json --------------------------------
                    String json = FileUtil.readFile(dataUrl);
                    ObjectMapper objMap = new ObjectMapper();
                    JsonNode root = objMap.readTree(json);
                    sceneAccidentPO = sceneAccidentPO.builder()
                            .accidentId(StringUtil.getRandomUUID())
                            .sceneName(root.path("场景名称").asText())
                            .scenceResume(root.path("场景描述").asText())
                            .selfDriving(root.path("自车驾驶行为").asText())
                            .targetDriving(root.path("目标驾驶行为").asText())
                            .selfReaction(root.path("自车反应行为").asText())
                            .conflictBehavior(root.path("冲突行为").asText())
                            .conflictType(root.path("冲突类型").asText())
                            .sceneTime(root.path("时间").asText())
                            .sceneWeather(root.path("天气").asText())
                            .maxTime(root.path("max_time").asText())
                            .isDeleted("0")
                            .build();
                    // -------------------------------- 保存数据到 mysql --------------------------------
                    sceneAccidentPO.setCreateTime(TimeUtil.getNowForMysql());
                    sceneAccidentPO.setCreateUserId(AuthUtil.getCurrentUserId());
                    sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());

                    if (null != param.getJsonAddress() && !param.getJsonAddress().equals("")) {
                        sceneAccidentPO.setJsonAddress(param.getJsonAddress());
                    }
                    if (null != param.getXmlAddress() && !param.getXmlAddress().equals("")) {
                        sceneAccidentPO.setXmlAddress(param.getXmlAddress());
                    }
                    if (null != param.getXodrAddress() && !param.getXodrAddress().equals("")) {
                        sceneAccidentPO.setXodrAddress(param.getXodrAddress());
                    }
                    if (null != param.getOsgbAddress() && !param.getOsgbAddress().equals("")) {
                        sceneAccidentPO.setOsgbAddress(param.getOsgbAddress());
                    }
                    if (null != param.getVideoAddress() && !param.getVideoAddress().equals("")) {
                        sceneAccidentPO.setVideoAddress(param.getVideoAddress());
                    }
                }
            }
            sceneAccidentMapper.saveSceneAccident(sceneAccidentPO);
        } catch (Exception e) {
            log.error("标准法规场景" + fileName + " 解析出错：", e);
        }
    }
*/

    public SceneEvaluationOperatePO getSceneEvaluationFirst(SceneAccidentParam params, List<String> sceneIdList) {
        // 添加复杂度 危险度数据
        SceneEvaluationForListParam sceneEvaluationForListParam = new SceneEvaluationForListParam();
        BeanUtils.copyProperties(params, sceneEvaluationForListParam);
        sceneEvaluationForListParam.setSceneIdList(sceneIdList);
        return sceneEvaluationRuleService.getSceneEvaluationFirst(sceneEvaluationForListParam);
    }

    public List<SceneAccidentPO> querySceneAccidentList(SceneAccidentParam params) {

        if (StringUtil.isNotEmpty(params.getComplexityLevel()) || StringUtil.isNotEmpty(params.getMinComplexity()) || StringUtil.isNotEmpty(params.getMaxComplexity())) {
            params.setNeedComplexity("1");
        }
        if (StringUtil.isNotEmpty(params.getRiskLevel()) || StringUtil.isNotEmpty(params.getMinRisk()) || StringUtil.isNotEmpty(params.getMaxRisk())) {
            params.setNeedRisk("1");
        }

        List<SceneAccidentPO> list = new ArrayList<>();
        String roleCode = AuthUtil.getCurrentUserRoleCode();
        log.info("交通事故查询------" + roleCode);
        String userId = AuthUtil.getCurrentUserId();
        if (DictConstants.ROLE_CODE_ADMIN.equals(roleCode) || DictConstants.ROLE_CODE_SYSADMIN.equals(roleCode)) { //管理员账户
            list = sceneAccidentMapper.querySceneAccidentList(params);
            log.info("泛华----list--" + list.size() + "----------" + params);
        } else if (DictConstants.ROLE_CODE_SUBUESR.equals(roleCode)) {
            //查询父账户
            userId = AuthUtil.getCreateUserId();
            params.setUserId(userId);
            if (params.getShare().equals("0")) {
                list = sceneAccidentMapper.querySceneAccidentList(params);
            } else {
                list = sceneAccidentMapper.querySceneAccidentListByQx(params);
            }
        } else if (DictConstants.ROLE_CODE_UESR.equals(roleCode)) {
            //查询普通账户
            params.setUserId(userId);
            if (params.getShare().equals("0")) {
                list = sceneAccidentMapper.querySceneAccidentList(params);
            } else {
                list = sceneAccidentMapper.querySceneAccidentListByQx(params);
            }

        }

     /*   if ((params.getXlk().equals("1") && params.getBq().equals(1)) || (params.getXlk().equals("0") && params.getBq().equals(0)) || (params.getXlk().equals("1") && params.getBq().equals(0))) {
            list = sceneAccidentMapper.querySceneAccidentList(params);
        }*//*else if(params.getXlk().equals("1")&&params.getBq().equals("0")){
            list = sceneAccidentMapper.querySceneAccidentListByXlk(params);
        }*//* else if (params.getXlk().equals("0") && params.getBq().equals(1)) {
            list = sceneAccidentMapper.querySceneAccidentListByBq(params);
        }*/

        //追尾
       /* if(ObjectUtil.isNotNull(params.getRearEndCollision())){
            if(params.getConflictBehavior()!=null&&params.getConflictBehavior().size()>0){
                List<String> ConflictBehavior= params.getConflictBehavior();
                ConflictBehavior.add(params.getRearEndCollision());
                params.setConflictBehavior(ConflictBehavior);
            }else{
                List<String> ConflictBehavior=new ArrayList<>();
                ConflictBehavior.add(params.getRearEndCollision());
                        params.setConflictBehavior(ConflictBehavior);
            }
        }
        if(ObjectUtil.isNotNull(params.getCutIn())){
            if(params.getTargetDriving()!=null&&params.getTargetDriving().size()>0){
                List<String> targetDriving= params.getTargetDriving();
                targetDriving.add(params.getCutIn());
                params.setTargetDriving(targetDriving);
            }else{
                List<String> targetDriving=new ArrayList<>();
                targetDriving.add(params.getCutIn());
                params.setTargetDriving(targetDriving);
            }
        }
        if(ObjectUtil.isNotNull(params.getDriveCurve())){
            if(params.getTargetDriving()!=null&&params.getTargetDriving().size()>0){
                List<String> targetDriving= params.getTargetDriving();
                targetDriving.add(params.getDriveCurve());
                params.setTargetDriving(targetDriving);
            }else{
                List<String> targetDriving=new ArrayList<>();
                targetDriving.add(params.getDriveCurve());
                params.setTargetDriving(targetDriving);
            }
        }
        if(ObjectUtil.isNotNull(params.getCarConflict())){
            if(params.getConflictType()!=null&&params.getConflictType().size()>0){
                List<String> conflictType= params.getConflictType();
                conflictType.add(params.getCarConflict());
                params.setConflictType(conflictType);
            }else{
                List<String> conflictType=new ArrayList<>();
                conflictType.add(params.getCarConflict());
                params.setConflictType(conflictType);
            }
        }*/

        //获取权限并赋值
        /*List<String> listType=  systemUserSceneService.querySystemUserSceneByType(DictConstants.SCENE_ACCIDENT);
        if(listType!=null&&listType.size()>0){
            params.setAllIds(listType);
        }else{
            List<String> listA=new ArrayList<>();
            listA.add("没有权限");
            params.setAllIds(listA);
        }*/

        for (SceneAccidentPO po : list) {
            if (po.getConflictBehavior().contains("追尾")) {
                po.setLabel("追尾");
            }
            if (po.getTargetDriving().contains("切入")) {
                if (ObjectUtil.isNull(po.getLabel())) {
                    po.setLabel("目标车切入");
                } else {
                    po.setLabel(po.getLabel() + ",目标车切入");
                }

            }
            if (po.getTargetDriving().contains("沿弯道行驶")) {
                if (ObjectUtil.isNull(po.getLabel())) {
                    po.setLabel("目标车沿弯道行驶");
                } else {
                    po.setLabel(po.getLabel() + ",目标车沿弯道行驶");
                }

            }
            if (po.getConflictType().contains("机动车-机动车")) {
                if (ObjectUtil.isNull(po.getLabel())) {
                    po.setLabel("机动车-机动车冲突");
                } else {
                    po.setLabel(po.getLabel() + ",机动车-机动车冲突");
                }
            }
        }

        return list;
    }


    public List<SceneAccidentPO> querySceneAccidentListByQx(SceneAccidentParam params) {
        if (ObjectUtil.isNotNull(params.getSceneName()) || (params.getSelfDriving() != null && params.getSelfDriving().size() > 0) || (params.getTargetDriving() != null && params.getTargetDriving().size() > 0)
                || (params.getSelfReaction() != null && params.getSelfReaction().size() > 0) || (params.getConflictType() != null && params.getConflictType().size() > 0) || (params.getConflictBehavior() != null && params.getConflictBehavior().size() > 0) || (params.getIds() != null && params.getIds().length > 0)) {
            params.setXlk("1");
        }
        if (ObjectUtil.isNotNull(params.getRearEndCollision()) || ObjectUtil.isNotNull(params.getCutIn()) || ObjectUtil.isNotNull(params.getDriveCurve()) || ObjectUtil.isNotNull(params.getCarConflict())) {
            params.setBq(1);
        }
        List<SceneAccidentPO> list = new ArrayList<>();
        if ((params.getXlk().equals("1") && params.getBq().equals(1)) || (params.getXlk().equals("0") && params.getBq().equals(0)) || (params.getXlk().equals("1") && params.getBq().equals(0))) {
            list = sceneAccidentMapper.querySceneAccidentList(params);
        } else if (params.getXlk().equals("0") && params.getBq().equals(1)) {
            list = sceneAccidentMapper.querySceneAccidentListByBq(params);
        }


        for (SceneAccidentPO po : list) {
            if (po.getConflictBehavior().contains("追尾")) {
                po.setLabel("追尾");
            }
            if (po.getTargetDriving().contains("切入")) {
                if (ObjectUtil.isNull(po.getLabel())) {
                    po.setLabel("目标车切入");
                } else {
                    po.setLabel(po.getLabel() + ",目标车切入");
                }

            }
            if (po.getTargetDriving().indexOf("沿弯道行驶") > -1) {
                if (ObjectUtil.isNull(po.getLabel())) {
                    po.setLabel("目标车沿弯道行驶");
                } else {
                    po.setLabel(po.getLabel() + ",目标车沿弯道行驶");
                }

            }
            if (po.getConflictType().indexOf("机动车-机动车") > -1) {
                if (ObjectUtil.isNull(po.getLabel())) {
                    po.setLabel("机动车-机动车冲突");
                } else {
                    po.setLabel(po.getLabel() + ",机动车-机动车冲突");
                }
            }
        }

        return list;
    }

    @Transactional
    public void batchDeleteSceneAccident(List<String> sceneNames) {
        deleteSceneAccidentList(sceneNames);
    }

    @SneakyThrows
    @Transactional
    public void deleteSceneAccidentList(List<String> sceneNames) {
        Map<String, String> map = new HashMap<>();
        try {
            //* -------------------------------- 场景表 --------------------------------
            //1 根据场景名称查询出同名的所有场景id，包括公有和私有
            List<String> sceneIds = sceneAccidentMapper.selectIdsByNames(sceneNames);
            if (CollectionUtil.isEmpty(sceneIds)) {
                return;
            }
            //2 删除场景数据
            SceneDeleteParam sceneDeleteParam = SceneDeleteParam.builder()
                    .sceneNames(sceneNames)
                    .modifyTime(TimeUtil.getNowForMysql())
                    .modifyUserId(AuthUtil.getCreateUserId())
                    .build();
            sceneAccidentMapper.deleteBySceneNames(sceneDeleteParam);
            //* -------------------------------- 场景测试包指标表 & 场景测试包表 --------------------------------
            //1 根据自然驾驶场景ID查询场景测试包指标
            List<ScenePackageSublistPO> indexes = scenePackageSublistMapper.selectBySceneIds(ScenePackageSublistParam.builder()
                    .sceneIds(sceneIds)
                    .sceneType(DictConstants.SCENE_ACCIDENT)
                    .build());
            if (CollectionUtil.isEmpty(indexes)) {
                return;
            }
            //2 根据指标ID查询场景测试包
            List<ScenePackagePO> testPackages = scenePackageMapper.selectByIndexIds(ScenePackageParam.builder()
                    .indexIds(indexes.stream().map(ScenePackageSublistPO::getSublistId).collect(Collectors.toList()))
                    .build());
            //3 设置包为已禁用
            testPackages.forEach(testPackage -> testPackage.setIsUnavailable(DictConstants.IS_UNAVAILABLE));
            //4 遍历删除场景
            AtomicInteger deleteNum = new AtomicInteger();
            indexes.forEach(index -> {
                final String sceneNaturalIdsString = index.getSceneNaturalIds();
                List<String> sceneNaturalIds = new ArrayList<>();
                if (StringUtil.isNotEmpty(sceneNaturalIdsString)) {
                    sceneNaturalIds = CollectionUtil.sequenceStringToList(sceneNaturalIdsString, ",");
                }
                final String sceneTrafficIdsString = index.getSceneTrafficIds();
                List<String> sceneTrafficIds = new ArrayList<>();
                if (StringUtil.isNotEmpty(sceneTrafficIdsString)) {
                    sceneTrafficIds = CollectionUtil.sequenceStringToList(sceneTrafficIdsString, ",");
                }
                final String sceneStatueIdsString = index.getSceneStatueIds();
                List<String> sceneStatueIds = new ArrayList<>();
                if (StringUtil.isNotEmpty(sceneStatueIdsString)) {
                    sceneStatueIds = CollectionUtil.sequenceStringToList(sceneStatueIdsString, ",");
                }
                final String sceneGeneralizationIdsString = index.getSceneGeneralizationIds();
                List<String> sceneGeneralizationIds = new ArrayList<>();
                if (StringUtil.isNotEmpty(sceneGeneralizationIdsString)) {
                    sceneGeneralizationIds = CollectionUtil.sequenceStringToList(sceneGeneralizationIdsString, ",");
                }
                final String sceneReferenceLibIds = index.getSceneReferenceLibIds();
                List<String> sceneReferenceLibIdList = new ArrayList<>();
                if (StringUtil.isNotEmpty(sceneReferenceLibIds)) {
                    sceneReferenceLibIdList = CollectionUtil.sequenceStringToList(sceneReferenceLibIds, ",");
                }

                final Iterator<String> iterator = sceneTrafficIds.iterator();
                while (iterator.hasNext()) {
                    final String sceneId = iterator.next();
                    if (sceneIds.contains(sceneId)) {
                        iterator.remove();
                        deleteNum.getAndIncrement();
                        testPackages.forEach(testPackage -> {
                            testPackage.setSceneNum(testPackage.getSceneNum() - 1);
                        });
                    }
                }
                index.setSceneNum(sceneNaturalIds.size() + sceneTrafficIds.size() + sceneStatueIds.size() + sceneGeneralizationIds.size() + sceneReferenceLibIdList.size());
//                index.setSceneNum(index.getSceneNum() - deleteNum.get());
                index.setSceneNaturalIds(CollectionUtil.listToSequence(sceneNaturalIds));
                index.setModifyTime(TimeUtil.getNowForMysql());
                index.setModifyUserId(AuthUtil.getCurrentUserId());
            });
            //5 更新指标
            scenePackageSublistMapper.update(indexes);
            //6 更新包
            scenePackageMapper.update(testPackages);

            //* -------------------------------- 场景包表 --------------------------------
            //1 将所有场景包中的该场景删除
            systemScenePackageSublistMapper.deleteBySceneNames(SystemScenePackageParam.builder()
                    .sceneNames(sceneNames)
                    .modifyTime(TimeUtil.getNowForMysql())
                    .modifyUserId(AuthUtil.getCurrentUserId())
                    .build());
        } finally {
            //* -------------------------------- 日志表 --------------------------------
            map.put("sceneNames", JsonUtil.listToJson(sceneNames));
            map.put("type", DictConstants.SCENE_NATURAL);
            logService.logSceneDelete(LogConstants.SYS_LOG_SCENE_DELETE, map);
        }
    }

    /*
     * 获取交通事故场景数据：
     *//*
    @SneakyThrows
    public ResponseBodyVO<String> saveAll(SceneAccidentParam param) {
        //1 获取所有目录下所有场景
        String dataUrl0 = "D:\\交通事故场景";     // 场景数据根路径
        //  System.out.println("--------"+param.getPath());
        File[] scenes = FileUtil.getDirectory(dataUrl0).listFiles();
        if (scenes == null) {
            throw new RuntimeException("目录：" + dataUrl0 + " 下没有文件！");
        }

        String fileName = null;
        try {
            List<SceneAccidentPO> list = new ArrayList<SceneAccidentPO>();
            List<SceneAccidentPO> updateList = new ArrayList<SceneAccidentPO>();
            Integer wJNum = 1;
            for (File scene1 : scenes) {
                String dataUrlNew = scene1.getAbsolutePath();
                File[] scenes1 = FileUtil.getDirectory(dataUrlNew).listFiles();
                if (scenes1 == null) {
                    throw new RuntimeException("目录：" + dataUrlNew + " 下没有文件！");
                }
                SceneAccidentPO sceneAccidentPO = new SceneAccidentPO();
                Integer nowTime = TimeUtil.getRq(new Date(), 0);
                for (File scene : scenes1) {
                    String dataUrl = scene.getAbsolutePath();
                    // File pdfFile = new File(dataUrl);
                    fileName = scene.getName();
                    //文件上传测试1  遍历拿到的文件scene
                   *//* FileInputStream inputStream = new FileInputStream(scene);
                    MultipartFile multipartFile = new MockMultipartFile("file", fileName, "text/plain", IOUtils.toByteArray(inputStream));
                 *//*
                    FileItem fileItem = XmlParse.createFileItem(scene.getPath(), scene.getName());
                    MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                    fileItem.delete();
                    //调用文件上传方法
                    String nowNum = nowTime + "" + wJNum;
                    String objectName = "交通事故场景1111/" + nowNum + "/" + fileName;
                    ResponseBodyVO<String> respon = fileDownService.upload(multipartFile, objectName);

                    if (dataUrl.indexOf(".json") != -1) {
                        // -------------------------------- 读取结构化数据文件 --------------------------------
                        // -------------------------------- label.json --------------------------------
                        String json = FileUtil.readFile(dataUrl);
                        ObjectMapper objMap = new ObjectMapper();
                        JsonNode root = objMap.readTree(json);
                        //判断是否存在
                        String sceneName = root.path("场景名称").asText();
                        String sceneId = sceneAccidentMapper.querySceneAccidentByNmae(root.path("场景名称").asText());
                        sceneAccidentPO = sceneAccidentPO.builder()
                                .accidentId(StringUtil.getRandomUUID())
                                .sceneName(root.path("场景名称").asText())
                                .scenceResume(root.path("场景描述").asText())
                                .selfDriving(root.path("自车驾驶行为").asText())
                                .targetDriving(root.path("目标驾驶行为").asText())
                                .selfReaction(root.path("自车反应行为").asText())
                                .conflictBehavior(root.path("冲突行为").asText())
                                .conflictType(root.path("冲突类型").asText())
                                .sceneTime(root.path("时间").asText())
                                .sceneWeather(root.path("天气").asText())
                                .maxTime(root.path("max_time").asText())
                                .isDeleted("0")
                                .build();
                        // -------------------------------- 保存数据到 mysql --------------------------------
                        //插入地址
                        if (null != objectName && objectName.indexOf(".json") != -1) {
                            sceneAccidentPO.setJsonAddress(objectName);
                        } else if (objectName.indexOf(".xml") != -1 || objectName.indexOf(".xosc") != -1) {
                            sceneAccidentPO.setXmlAddress(objectName);
                        } else if (null != objectName && objectName.indexOf(".xodr") != -1) {
                            sceneAccidentPO.setXodrAddress(objectName);
                        } else if (null != objectName && objectName.indexOf(".osgb") != -1) {
                            sceneAccidentPO.setOsgbAddress(objectName);
                        } else if (null != objectName && objectName.indexOf(".mp4") != -1) {
                            sceneAccidentPO.setVideoAddress(objectName);
                        }

                        if (ObjectUtil.isNull(sceneId)) {
                            sceneAccidentPO.setCreateTime(TimeUtil.getNowForMysql());
                            sceneAccidentPO.setCreateUserId(AuthUtil.getCurrentUserId());
                            sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());
                            // return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "该场景名称" + sceneName + "已存在，请检查");
                        } else {
                            sceneAccidentPO.setAccidentId(sceneId);
                            sceneAccidentPO.setModifyUserId(AuthUtil.getCurrentUserId());
                            sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());


                        }
                    }
                }
                if (ObjectUtil.isNull(sceneAccidentPO.getModifyUserId())) {
                    list.add(sceneAccidentPO);
                } else {
                    updateList.add(sceneAccidentPO);
                }
                wJNum++;
            }
            if (ObjectUtil.isNotNull(list)) {
                sceneAccidentMapper.saveSceneAccidentList(list);
            }
            if (ObjectUtil.isNotNull(updateList)) {
                sceneAccidentMapper.updateSceneAccidentList(updateList);
            }
            return new ResponseBodyVO(ResponseBodyVO.Response.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "该场景文件" + fileName + "解析出错");
        }

    }
*/
    /*
     * 获取交通事故场景数据：最新的自己获取路径
     */
   /* @SneakyThrows
    public ResponseBodyVO<String> saveAllNew(String dataUrl1) {
        //1 获取所有目录下所有场景
        // String dataUrl0 = "D:\\自然驾驶场景样例";     // 场景数据根路径
        String dataUrl0 = "D:\\自然驾驶场景样例\\2021\\20210806";
        File[] scenes = FileUtil.getDirectory(dataUrl0).listFiles();
        if (scenes == null) {
            throw new RuntimeException("目录：" + dataUrl0 + " 下没有文件！");
        }
        try {
            List<SceneAccidentPO> list = new ArrayList<SceneAccidentPO>();
            List<SceneAccidentPO> updateList = new ArrayList<SceneAccidentPO>();
            for (File scene1 : scenes) {
                String dataUrlNew = scene1.getAbsolutePath();
                File[] scenes1 = FileUtil.getDirectory(dataUrlNew).listFiles();
                if (scenes1 == null) {
                    throw new RuntimeException("目录：" + dataUrlNew + " 下没有文件！");
                }

                for (File scene : scenes1) {
                    //判断是否为场景文件夹
                    if (scene.isDirectory()) {
                        String dataUrlNew1 = scene.getAbsolutePath();
                        File[] scenes2 = FileUtil.getDirectory(dataUrlNew1).listFiles();
                        if (scenes2 == null) {
                            throw new RuntimeException("目录：" + dataUrlNew1 + " 下没有文件！");
                        }
                        SceneAccidentPO sceneAccidentPO = new SceneAccidentPO();
                        String isUpdate = "";
                        for (File scene3 : scenes2) {
                            String dataUrl = scene3.getAbsolutePath();
                            if (dataUrl.indexOf(".json") != -1) {
                                // -------------------------------- 读取结构化数据文件 --------------------------------
                                // -------------------------------- label.json --------------------------------
                                String json = FileUtil.readFile(dataUrl);
                                ObjectMapper objMap = new ObjectMapper();
                                JsonNode root = objMap.readTree(json);
                                //判断是否存在
                                String sceneName = root.path("场景名称").asText();
                                String sceneId = sceneAccidentMapper.querySceneAccidentByNmae(sceneName);
                                sceneAccidentPO = sceneAccidentPO.builder()
                                        .accidentId(StringUtil.getRandomUUID())
                                        .sceneName(sceneName)
                                        .scenceResume(root.path("场景描述").asText())
                                        .selfDriving(root.path("自车驾驶行为").asText())
                                        .targetDriving(root.path("目标驾驶行为").asText())
                                        .selfReaction(root.path("自车反应行为").asText())
                                        .conflictBehavior(root.path("冲突行为").asText())
                                        .conflictType(root.path("冲突类型").asText())
                                        .sceneTime(root.path("时间").asText())
                                        .sceneWeather(root.path("天气").asText())
                                        .maxTime(root.path("max_time").asText())
                                        .isDeleted("0")
                                        .build();

                                String xodrAderss = root.path("xodr").asText();
                                String osgbAderss = root.path("osgb").asText();
                                sceneAccidentPO.setOsgbAddress(dataUrl0 + osgbAderss);
                                sceneAccidentPO.setXodrAddress(dataUrl0 + xodrAderss);
                                // -------------------------------- 保存数据到 mysql --------------------------------
                                if (ObjectUtil.isNull(sceneId)) {
                                    isUpdate = "0";
                                    sceneAccidentPO.setCreateTime(TimeUtil.getNowForMysql());
                                    sceneAccidentPO.setCreateUserId(AuthUtil.getCurrentUserId());
                                    sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());
                                    // return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "该场景名称" + sceneName + "已存在，请检查");
                                } else {
                                    isUpdate = "1";
                                    sceneAccidentPO.setAccidentId(sceneId);
                                    sceneAccidentPO.setModifyUserId(AuthUtil.getCurrentUserId());
                                    sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());

                                }
                            }
                            //插入地址
                            if (dataUrl.indexOf(".json") != -1) {
                                sceneAccidentPO.setJsonAddress(dataUrl);
                            } else if (dataUrl.indexOf(".xml") != -1 || dataUrl.indexOf(".xosc") != -1) {
                                sceneAccidentPO.setXmlAddress(dataUrl);
                            } *//*else if (dataUrl.indexOf(".xodr") != -1) {
                        sceneAccidentPO.setXodrAddress(dataUrl);
                    } else if (dataUrl.indexOf(".osgb") != -1) {
                        sceneAccidentPO.setOsgbAddress(dataUrl);
                    }*//* else if (dataUrl.indexOf("simulation.mp4") != -1) {
                                sceneAccidentPO.setVideoAddress(dataUrl);
                            } else if (dataUrl.indexOf("simulation.mp4") == -1 && dataUrl.indexOf(".mp4") != -1) {
                                sceneAccidentPO.setVideoPreview(dataUrl);
                            }

                        }
                        if (isUpdate.equals("0")) {
                            list.add(sceneAccidentPO);
                        } else if (isUpdate.equals("1")) {
                            updateList.add(sceneAccidentPO);
                        }

                    }

                }

            }
            if (ObjectUtil.isNotNull(list)) {
                sceneAccidentMapper.saveSceneAccidentList(list);
            }
            if (ObjectUtil.isNotNull(updateList)) {
                sceneAccidentMapper.updateSceneAccidentList(updateList);
            }
            return new ResponseBodyVO(ResponseBodyVO.Response.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseBodyVO(ResponseBodyVO.Response.CLIENT_FAILURE, "该场景文件" + dataUrl0 + "解析出错");
        }


    }*/

/*    public static FileItem createFileItem(String filePath, String fileName){
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory();
        FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(newfile);
             OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
            {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }*/


    /**
     * 获取交通事故场景数据：现在
     */
    public SceneImportPO importMiNio(SceneImportParam params) {
        SceneImportPO sceneImportPO = new SceneImportPO();
        sceneImportPO.setId(params.getId());
        try {
            MinioParameter MI = new MinioParameter();
            MI.setObjectName(params.getMinioDirectory());
            List<String> list = fileDownService.listDeepOne(MI).getInfo();
            String OsgbPath = null;
            String XodrPath = null;
            int successNum = 0;
            int falseNum = 0;
            String errorMessage = "";
            for (String filePath : list) {
                if (filePath.contains("/OSGB")) {
                    OsgbPath = filePath;
                } else if (filePath.contains("/XODR")) {
                    XodrPath = filePath;
                }
            }
            List<String> sceneNames = new ArrayList<>();
            for (String filePath : list) {
                if (filePath.contains("/Scenarios")) {
                    MI.setObjectName(filePath);
                    List<String> listScene = fileDownService.listDeepOne(MI).getInfo();
                    log.info("共需要上传 " + listScene.size() + " 个交通事故场景");
                    String taskId = api.common.util.StringUtil.getRandomUUID();
                    SceneEvaluationComputeParam sceneComplexityEvaluationComputeParam = new SceneEvaluationComputeParam();
                    sceneComplexityEvaluationComputeParam.setSceneEvaluationComputeSubParam(new ArrayList<>());
                    for (String scenePath : listScene) {
                        try {
                            MI.setObjectName(scenePath);
                            List<String> listAderss = fileDownService.listDeepOne(MI).getInfo();
                            SceneAccidentPO sceneAccidentPO = new SceneAccidentPO();
                            String isupdate = null;
                            String sceneName;
                            List<SceneAccidentPO> scenes = new ArrayList<>();
                            for (String adress : listAderss) {
                                if (adress.contains(".json")) {
                                    MI.setObjectName(adress);
                                    Response download = fileDownService.download(MI);
                                    // -------------------------------- label.json --------------------------------
                                    String json = download.body().toString();
                                    ObjectMapper objMap = new ObjectMapper();
                                    JsonNode root = objMap.readTree(json);
                                    // 判断场景名称唯一
                                    sceneName = root.path("场景名称").asText();
                                    sceneNames.add(sceneName);
                                    String selfDriving = root.path("自车驾驶行为").asText();
                                    String conflictBehavior = root.path("冲突行为").asText();
                                    String conflictType = root.path("冲突类型").asText();
                                    String selfReaction = root.path("自车反应行为").asText();
                                    if (ObjectUtil.isNull(sceneName) || ObjectUtil.isNull(selfDriving) || ObjectUtil.isNull(conflictType) || ObjectUtil.isNull(conflictBehavior)) {
                                        sceneImportPO.setStatus(DictConstants.SCENE_IMPORT_STATUS_2);
                                        String em = "文件 " + adress + " 内容不符合标准格式（场景名称、自车驾驶行为、冲突行为、冲突类型不能为空）。";
                                        log.error(em);
                                        sceneImportPO.setErrorMessage(em);
                                        return sceneImportPO;
                                    }

                                    sceneAccidentPO.setSceneName(sceneName);
                                    sceneAccidentPO.setShare(null);// 覆盖全部场景，包括share为0、1、2
//                                    sceneAccidentPO.setShare("0");
//                                    SceneAccidentPO sceneAccidentPOByName = sceneAccidentMapper.querySceneAccidentByNmae(sceneAccidentPO);
                                    scenes = sceneAccidentMapper.selectAllByName(sceneAccidentPO);
                                    if (CollectionUtil.isEmpty(scenes)) { // 新增数据
                                        isupdate = "0";
                                    } else {    // 覆盖（更新）数据
                                        isupdate = "1";
                                    }
                                    String osgbAdress = OsgbPath + "/" + root.path("osgb").asText();
                                    String xodrAdress = XodrPath + "/" + root.path("xodr").asText();
                                    sceneAccidentPO.setScenceResume(root.path("场景描述").asText());
                                    sceneAccidentPO.setSelfDriving(selfDriving);
                                    sceneAccidentPO.setTargetDriving(root.path("目标驾驶行为").asText());
                                    sceneAccidentPO.setSelfReaction(selfReaction);
                                    sceneAccidentPO.setConflictBehavior(conflictBehavior);
                                    sceneAccidentPO.setConflictType(conflictType);
                                    sceneAccidentPO.setSceneTime(root.path("时间").asText());
                                    sceneAccidentPO.setSceneWeather(root.path("天气").asText());
                                    sceneAccidentPO.setMaxTime(root.path("max_time").asText());
                                    sceneAccidentPO.setIsDeleted("0");

                                    if (ObjectUtil.isNull(sceneAccidentPO.getOsgbAddress())) {
                                        sceneAccidentPO.setOsgbAddress(osgbAdress);
                                    }
                                    if (ObjectUtil.isNull(sceneAccidentPO.getXodrAddress())) {
                                        sceneAccidentPO.setXodrAddress(xodrAdress);
                                    }

                                }
                                if (adress.contains(".json")) {
                                    sceneAccidentPO.setJsonAddress(adress);
                                } else if (adress.contains(".xml") || adress.contains(".xosc")) {
                                    sceneAccidentPO.setXmlAddress(adress);
                                } else if (adress.contains(".xodr")) {
                                    sceneAccidentPO.setXodrAddress(adress);
                                } else if (adress.contains(".osgb")) {
                                    sceneAccidentPO.setOsgbAddress(adress);
                                } else if (adress.contains(".mp4")) {
                                    sceneAccidentPO.setVideoAddress(adress);
                                }
                            }
                            if (isupdate.equals("0")) {
                                // -------------------------------- 新增数据到 mysql --------------------------------
                                sceneAccidentPO.setShare(DictConstants.IS_NOT_SHARED);
                                sceneAccidentPO.setAccidentId(StringUtil.getRandomUUID());
                                sceneAccidentPO.setCreateTime(TimeUtil.getNowForMysql());
                                sceneAccidentPO.setCreateUserId(AuthUtil.getCurrentUserId());
                                sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());
                                sceneAccidentMapper.saveSceneAccident(sceneAccidentPO);

                            } else if (isupdate.equals("1")) {
                                // -------------------------------- 修改数据到 mysql --------------------------------
                                if (StringUtil.isEmpty(sceneAccidentPO.getShare())) {
                                    sceneAccidentPO.setShare(DictConstants.IS_NOT_SHARED);
                                }
                                scenes.forEach(scene -> {
                                    sceneAccidentPO.setAccidentId(scene.getAccidentId());
                                    sceneAccidentPO.setModifyTime(TimeUtil.getNowForMysql());
                                    sceneAccidentPO.setModifyUserId(AuthUtil.getCurrentUserId());
                                    sceneAccidentMapper.updateSceneAccident(sceneAccidentPO);
                                });
                            }

                            successNum = successNum + 1;

                            // 计算复杂度
                            if (!StringUtils.isEmpty(params.getSceneEvaluationRuleId())) {
                                SceneEvaluationComputeSubParam sceneEvaluationComputeSubParam = new SceneEvaluationComputeSubParam();
                                sceneEvaluationComputeSubParam.setSceneId(isupdate.equals("0") ? sceneAccidentPO.getAccidentId() : scenes.get(0).getAccidentId());
                                sceneEvaluationComputeSubParam.setSceneXOSCPath(sceneAccidentPO.getXmlAddress());
                                sceneEvaluationComputeSubParam.setSceneXODRPath(sceneAccidentPO.getXodrAddress());
                                sceneEvaluationComputeSubParam.setSceneType(DictConstants.SCENE_ACCIDENT);
                                if (isupdate.equals("1")) {
                                    String tempSceneId = scenes.get(0).getAccidentId();
                                    sceneEvaluationComputeSubParam.setCopySceneId(scenes.stream().map(SceneAccidentPO::getAccidentId).filter(sceneId -> !StringUtils.equals(tempSceneId, sceneId)).collect(Collectors.toList()));
                                }
                                sceneComplexityEvaluationComputeParam.getSceneEvaluationComputeSubParam().add(sceneEvaluationComputeSubParam);
                            }
                        } catch (Exception e) {
                            errorMessage = e.getMessage();
                            e.printStackTrace();
                            falseNum = falseNum + 1;
                        }
                    }
                    try {
                        if (CollectionUtil.isNotEmpty(sceneComplexityEvaluationComputeParam.getSceneEvaluationComputeSubParam())) {
                            sceneComplexityEvaluationComputeParam.setTaskId(taskId);
                            sceneComplexityEvaluationComputeParam.setSceneEvaluationRuleId(params.getSceneEvaluationRuleId());
                            sceneComplexityEvaluationComputeParam.setComputeType(DictConstants.COMPLEXITY);
                            sceneComplexityEvaluationComputeParam.setCreateUserId(AuthUtil.getCurrentUserId());
                            sceneEvaluationRuleService.computeSceneEvaluation(sceneComplexityEvaluationComputeParam);
                        }
                    } catch (Exception e) {
                        log.error("计算复杂度失败", e);
                    }
                }
            }
            sceneImportPO.setStatus(DictConstants.SCENE_IMPORT_STATUS_4);
            sceneImportPO.setSuccessNum(successNum);
            sceneImportPO.setFalseNum(falseNum);
            sceneImportPO.setErrorMessage(errorMessage);
            sceneImportPO.setSceneNames(CollectionUtil.listToSequence(sceneNames));
            return sceneImportPO;
        } catch (Exception e) {
            sceneImportPO.setErrorMessage("该文件地址：" + params.getMinioDirectory() + "解析失败，请检查");
            sceneImportPO.setStatus(DictConstants.SCENE_IMPORT_STATUS_2);
            return sceneImportPO;
        }
    }


    /**
     * 分享
     */
    public void instShareSceneAccident(SceneAccidentPO po) {
        SceneAccidentPO syPO = sceneAccidentMapper.querySceneAccidentById(po.getAccidentId());
        syPO.setShare("1");
        SceneAccidentPO sceneAccidentPOByName = sceneAccidentMapper.querySceneAccidentByNmae(syPO);
        if (ObjectUtil.isNull(sceneAccidentPOByName)) {
            // -------------------------------- 保存数据到 mysql --------------------------------
            syPO.setCreateTime(TimeUtil.getNowForMysql());
            syPO.setCreateUserId(AuthUtil.getCurrentUserId());
            syPO.setModifyTime(TimeUtil.getNowForMysql());
            syPO.setModifyUserId("");
            syPO.setAccidentId(StringUtil.getRandomUUID());
            sceneAccidentMapper.saveSceneAccident(syPO);
        } else {
            // -------------------------------- 修改数据到 mysql --------------------------------
            syPO.setModifyTime(TimeUtil.getNowForMysql());
            syPO.setModifyUserId(AuthUtil.getCurrentUserId());
            syPO.setAccidentId(sceneAccidentPOByName.getAccidentId());
            sceneAccidentMapper.updateSceneAccident(syPO);
        }

    }


}
