package com.fdkankan.scene.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.config.FileRouteConfig;
import com.fdkankan.common.constant.CameraConstant;
import com.fdkankan.common.constant.CommonStatus;
import com.fdkankan.common.constant.Constant;
import com.fdkankan.common.constant.ConstantFilePath;
import com.fdkankan.common.constant.ConstantUrl;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.SceneStatus;
import com.fdkankan.common.constant.TbStatus;
import com.fdkankan.common.constant.UploadFilePath;
import com.fdkankan.common.constant.UploadStatus;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.common.user.SSOUser;
import com.fdkankan.common.util.ComputerUtil;
import com.fdkankan.common.util.CreateObjUtil;
import com.fdkankan.common.util.DateExtUtil;
import com.fdkankan.common.util.FileMd5Util;
import com.fdkankan.common.util.FileUpload;
import com.fdkankan.common.util.FileUtil;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.common.util.MatrixToImageWriterUtil;
import com.fdkankan.common.util.RSAEncrypt;
import com.fdkankan.common.util.SnowflakeIdGenerator;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.platform.api.dto.Camera;
import com.fdkankan.platform.api.dto.CameraDetail;
import com.fdkankan.platform.api.dto.Company;
import com.fdkankan.platform.api.feign.PlatformGoodsClient;
import com.fdkankan.platform.api.feign.PlatformUserClient;
import com.fdkankan.rabbitmq.bean.BuildSceneCallMessage;
import com.fdkankan.rabbitmq.util.RabbitMqProducer;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.scene.entity.PicSceneProgress;
import com.fdkankan.scene.entity.Scene;
import com.fdkankan.scene.entity.SceneCooperation;
import com.fdkankan.scene.entity.SceneEditControls;
import com.fdkankan.scene.entity.SceneEditInfo;
import com.fdkankan.scene.entity.SceneEditInfoExt;
import com.fdkankan.scene.entity.SceneExt;
import com.fdkankan.scene.entity.SceneFileBuild;
import com.fdkankan.scene.entity.SceneFileUpload;
import com.fdkankan.scene.entity.ScenePO;
import com.fdkankan.scene.entity.ScenePlus;
import com.fdkankan.scene.entity.ScenePlusExt;
import com.fdkankan.scene.entity.ScenePro;
import com.fdkankan.scene.entity.SceneProEdit;
import com.fdkankan.scene.entity.SceneProEditExt;
import com.fdkankan.scene.entity.SceneProExt;
import com.fdkankan.scene.entity.SceneProPO;
import com.fdkankan.scene.entity.SceneResourceCamera;
import com.fdkankan.scene.entity.SceneResourceCooperation;
import com.fdkankan.scene.entity.VideoSceneProgress;
import com.fdkankan.scene.mapper.ISceneFileBuildMapper;
import com.fdkankan.scene.service.IFdkkLaserService;
import com.fdkankan.scene.service.IPicSceneProgressService;
import com.fdkankan.scene.service.IScene3dNumService;
import com.fdkankan.scene.service.ISceneCooperationService;
import com.fdkankan.scene.service.ISceneEditControlsService;
import com.fdkankan.scene.service.ISceneEditInfoExtService;
import com.fdkankan.scene.service.ISceneEditInfoService;
import com.fdkankan.scene.service.ISceneExtService;
import com.fdkankan.scene.service.ISceneFileBuildService;
import com.fdkankan.scene.service.ISceneFileUploadService;
import com.fdkankan.scene.service.IScenePlusExtService;
import com.fdkankan.scene.service.IScenePlusService;
import com.fdkankan.scene.service.ISceneProEditExtService;
import com.fdkankan.scene.service.ISceneProEditService;
import com.fdkankan.scene.service.ISceneProExtService;
import com.fdkankan.scene.service.ISceneProService;
import com.fdkankan.scene.service.ISceneResourceCameraService;
import com.fdkankan.scene.service.ISceneResourceCooperationService;
import com.fdkankan.scene.service.ISceneService;
import com.fdkankan.scene.service.IVideoSceneProgressService;
import com.fdkankan.scene.vo.BuildSceneParamVO;
import com.fdkankan.scene.vo.RebuildVedioSceneParamVO;
import com.fdkankan.scene.vo.ResponseSceneFile;
import com.fdkankan.scene.vo.ScenePlusVO;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 场景文件建模表 服务实现类
 * </p>
 *
 * @author dengsixing
 * @since 2021-12-23
 */
@Slf4j
@Service
public class SceneFileBuildServiceImpl extends ServiceImpl<ISceneFileBuildMapper, SceneFileBuild> implements ISceneFileBuildService {

    private static final String SPLICE = "#";

    @Value("${main.url}")
    private String mainUrl;

    @Value("${scene.url}")
    private String sceneUrl;

    @Value("${scene.pro.url}")
    private String sceneProUrl;

    @Value("${scene.pro.new.url}")
    private String sceneProNewUrl;

    @Value("${upload.type}")
    private String type;

    @Value("${oss.prefix.ali}")
    private String prefixAli;

    @Value("${ecs.type}")
    private String ecsType;

    @Value("${unCalculated.company.ids:#{null}}")
    private String[] unCalculatedCompanyIds;

    @Value("${queue.modeling.modeling-call}")
    private String queueModelingCall;
    @Value("${queue.modeling.modeling-pre}")
    private String queueModelingPre;

    @Value("${queue.modeling.video-a}")
    private String queueVideoA;

    @Value("${queue.modeling.pic-a}")
    private String queuePicA;

    @Autowired
    private IScenePlusService scenePlusService;
    @Autowired
    private IScenePlusExtService scenePlusExtService;
    @Autowired
    IPicSceneProgressService picSceneProgressService;
    @Autowired
    IVideoSceneProgressService videoSceneProgressService;
    @Autowired
    PlatformGoodsClient platformGoodsClient;
    @Autowired
    PlatformUserClient platformUserClient;
    @Autowired
    ISceneFileUploadService sceneFileUploadService;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    private FileRouteConfig routeConfig;
    @Autowired
    UploadToOssUtil uploadToOssUtil;
    @Autowired
    ISceneProEditService sceneProEditService;
    @Autowired
    ISceneProEditExtService sceneProEditExtService;
    @Autowired
    IScene3dNumService scene3dNumService;
    @Autowired
    ISceneProExtService sceneProExtService;
    @Autowired
    ISceneCooperationService sceneCooperationService;
    @Autowired
    ISceneResourceCameraService sceneResourceCameraService;
    @Autowired
    ISceneResourceCooperationService sceneResourceCooperationService;
    @Autowired
    RabbitMqProducer rabbitMqProducer;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISceneService sceneService;
    @Autowired
    ISceneExtService sceneExtService;
    @Autowired
    IFdkkLaserService fdkkLaserService;
    @Autowired
    ISceneEditInfoService sceneEditInfoService;
    @Autowired
    ISceneEditControlsService sceneEditControlsService;
    @Autowired
    ISceneEditInfoExtService sceneEditInfoExtService;

    @Override
    public SceneFileBuild findByFileId(String fileId) {

        List<SceneFileBuild> list = this.list(new LambdaQueryWrapper<SceneFileBuild>()
                .eq(SceneFileBuild::getTbStatus, TbStatus.VALID.code())
                .eq(SceneFileBuild::getFileId, fileId)
                .orderByDesc(SceneFileBuild::getId));
        if(CollUtil.isEmpty(list))
            return null;

        return list.get(0);
    }

    @Override
    public boolean uploadSuccess(String fileId, StringBuilder filePathBuffer) {
        SceneFileBuild sceneFileBuild = findByFileId(fileId);
        if (Objects.isNull(sceneFileBuild))
            return false;

        Long uploadSuccessCount = sceneFileUploadService.countUploadSuccessByFileId(fileId);
        sceneFileBuild.setUploadStatus(UploadStatus.SUCCESS.code());
        sceneFileBuild.setChunks(Integer.valueOf(uploadSuccessCount.toString()));
        sceneFileBuild.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(sceneFileBuild);
        return true;
    }

    @Override
    public SceneFileBuild findByUnicode(String unicode) {
        List<SceneFileBuild> list = this.list(new QueryWrapper<SceneFileBuild>()
                .eq("tb_status", TbStatus.VALID.code())
                .eq("unicode", unicode)
                .orderByDesc("id"));
        if(CollUtil.isEmpty(list))
            return null;

        return list.get(0);
    }

    @Async
    @Override
    public void unzipSingleFile(String filePath) {
        log.info("文件路径:{}", filePath);
        File file = new File(filePath);
        if (file.exists()){
            log.error(filePath + "：文件不存在");
            throw new BusinessException(ErrorCode.FAILURE_CODE_5038);
        }
        String parentFilePath = file.getParentFile().getPath();
        log.info("解压目标目录:{}", parentFilePath);
        StringBuffer exec = new StringBuffer(" tar xvf  ");
        exec.append(filePath);
        exec.append(" -C ").append(parentFilePath).append(File.separator);
        System.out.println(exec.toString());
        String[] cmdExec = new String[]{"/bin/sh", "-c", exec.toString()};
        int code = executeLinuxShell(cmdExec);
        if (code == 0){
            log.info("解压完成,文件路径：{}, 开始执行删除压缩文件", filePath);
            file.delete();
        }else {
            log.error("解压失败，文件路径：{}，解压状态：{}", filePath, code);
        }
    }

    private int executeLinuxShell(String[] command) {
        Process shellProcess = null;
        BufferedReader shellErrorResultReader = null;
        BufferedReader shellInfoResultReader = null;
        try {
            shellProcess = Runtime.getRuntime().exec(command);
            shellErrorResultReader = new BufferedReader(new InputStreamReader(shellProcess.getErrorStream()));
            shellInfoResultReader = new BufferedReader(new InputStreamReader(shellProcess.getInputStream()));
            String infoLine;
            while ((infoLine = shellInfoResultReader.readLine()) != null) {
                log.info("linux环境脚本执行信息:{}", infoLine);
            }
            String errorLine;
            while ((errorLine = shellErrorResultReader.readLine()) != null) {
                log.warn("linux环境脚本执行信息:{}", errorLine);
            }
            // 等待程序执行结束并输出状态
            int exitCode = shellProcess.waitFor();
            if (0 == exitCode) {
                log.info("linux环境脚本执行成功");
            } else {
                log.error("linux环境脚本执行失败:" + exitCode);
            }
            return exitCode;
        } catch (Exception e) {
            log.error("linux环境shell脚本执行错误", e);
            return 1;
        } finally {
            if (null != shellInfoResultReader) {
                try {
                    shellInfoResultReader.close();
                } catch (IOException e) {
                    log.error("linux环境脚本流文件关闭异常：", e);
                }
            }
            if (null != shellErrorResultReader) {
                try {
                    shellErrorResultReader.close();
                } catch (IOException e) {
                    log.error("linux环境脚本流文件关闭异常：", e);
                }
            }
            if (null != shellProcess) {
                shellProcess.destroy();
            }
        }
    }

    @Override
    public ResponseSceneFile preUpload(String params) throws Exception {
        log.info("preUpload-params: "+params);
        if (StrUtil.isEmpty(params)){
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        params = params.replaceAll("%2B", "+");
        Base64 base64 = new Base64();
        String cipher = params;
        // 私钥解密过程
        byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile()),
                base64.decode(cipher));
        String restr = new String(res, "UTF-8");
        log.debug("preUpload-params解密结果：" + restr);
        String[] strArr = restr.split(SPLICE);
        if (strArr.length != 5) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        String mac = strArr[0];
        String totalPicNum = strArr[1];
        String chunks = strArr[2];
        String folderName = strArr[3];

        if (StrUtil.isEmpty(mac)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5044);
        }
        if (totalPicNum == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5045);
        }
        if (chunks == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5046);
        }
        if (folderName == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5047);
        }

        log.info("mac：" + mac + "准备上传文件");
        SceneProPO scenePro = sceneProService.getSceneStatusByUnicode("/" + folderName, TbStatus.VALID.code());
        if(scenePro != null && scenePro.getDataSource() != null){
            int n = scenePro.getDataSource().split("/").length;
            if(n > 1){
                String fileId = scenePro.getDataSource().split("/")[n - 2];

                ResponseSceneFile responseSceneFile = new ResponseSceneFile();
                responseSceneFile.setFileId(fileId);
                //可以重复上传，文件id保存50年（因为该redis工具无法设置永久保存）
                redisUtil.set(fileId, folderName, 1537920000);
                return responseSceneFile;
            }

        }else {
            SceneFileBuild sceneFileBuild = this.findByUnicode(folderName);
            if(sceneFileBuild != null){
                String fileId = sceneFileBuild.getFileId();

                ResponseSceneFile responseSceneFile = new ResponseSceneFile();
                responseSceneFile.setFileId(fileId);
                //可以重复上传，文件id保存50年（因为该redis工具无法设置永久保存）
                redisUtil.set(fileId, folderName, 1537920000);
                return responseSceneFile;
            }
        }

        // 构造方法设置机器码：第0个机房的第0台机器
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(0, 0);
        long fileId = snowflakeIdGenerator.nextId();

        SceneFileBuild sceneFileBuild = new SceneFileBuild();
        sceneFileBuild.setChildName(mac);
        sceneFileBuild.setFileId(String.valueOf(fileId));
        sceneFileBuild.setUnicode(folderName);
        sceneFileBuild.setUploadStatus(0);
        sceneFileBuild.setBuildStatus(0);
        sceneFileBuild.setTotalPicNum(Integer.valueOf(totalPicNum));
        sceneFileBuild.setChunks(Integer.valueOf(chunks));
        this.save(sceneFileBuild);

        ResponseSceneFile responseSceneFile = new ResponseSceneFile();
        responseSceneFile.setFileId(String.valueOf(fileId));
        //可以重复上传，文件id保存50年（因为该redis工具无法设置永久保存）
        redisUtil.set(String.valueOf(fileId), folderName, 1537920000);
        return responseSceneFile;
    }

    @Override
    public ResponseSceneFile getProgress(String params) throws Exception {
        log.info("getProgress-params:{} ", params);
        if (StrUtil.isEmpty(params)){
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        params = params.replaceAll("%2B", "+");
        Base64 base64 = new Base64();
        String cipher = params;
        // 私钥解密过程
        byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile()),
                base64.decode(cipher));
        String restr = new String(res, "UTF-8");
        log.debug("getProgress-params解密结果：{}" , restr);
        String[] strArr = restr.split(SPLICE);
        if (strArr.length != 3) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        String fileId = strArr[0];
        String chunk = strArr[1];

        chunk = chunk.split(SPLICE)[0];
        SceneFileUpload sceneFileUpload = sceneFileUploadService.findByFileIdAndChunk(fileId, Integer.valueOf(chunk));

        ResponseSceneFile responseSceneFile = new ResponseSceneFile();
        responseSceneFile.setUploadStatus(sceneFileUpload != null ? sceneFileUpload.getUploadStatus() : -1);
        return responseSceneFile;
    }

    @Override
    public ResultData uploadFile(MultipartFile file, String params) throws Exception{
        log.info("upload-params: "+params);
        if (StringUtils.isEmpty(params)){
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        params = params.replaceAll("%2B", "+");
        Base64 base64 = new Base64();
        String cipher = params;
        // 私钥解密过程
        byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile()),
                base64.decode(cipher));
        String restr = new String(res, "UTF-8");
        log.debug("upload-params解密结果：{}", restr);
        String[] strArr = restr.split(SPLICE);
        if (strArr.length != 6) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        String mac = strArr[0];
        String fileId = strArr[1];
        String picNum = strArr[2];
        String md5 = strArr[3];
        String chunk = strArr[4];

        ResultData result = null;
        if (file.isEmpty()){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5048);
        }
        if (StringUtils.isEmpty(fileId)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5049);
        }
        if (picNum == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5050);
        }
        if (StringUtils.isEmpty(mac)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5044);
        }
        if (StringUtils.isEmpty(md5)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5051);
        }
        long size = file.getSize();
        log.warn("fileId:"+fileId+"---picNum:"+picNum+"---size:"+size+"---md5:"+md5+"---mac:"+mac);
        chunk = chunk.split(SPLICE)[0];
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        Object folderNameObject = redisUtil.get(fileId);
        String folderName = folderNameObject == null ? null : (String)folderNameObject;
        if(StringUtils.isEmpty(folderName)){
            SceneProPO scenePro = sceneProService.getSceneStatusByUnicode("/" + fileId + "/", TbStatus.VALID.code());
            if(scenePro != null){
                folderName = scenePro.getDataSource().substring(scenePro.getDataSource().lastIndexOf("/") + 1);
            }
        }
        // 1. 判断该文件是否已经上传过
        // 2. 如果已经上传过，判断MD5值和文件大小是否相等。如果相等，更新数据记录。如果不相等，删除该文件，重新上传。
        // 3. 如果未上传过，需要上传。
        StringBuffer filePathBuffer = new StringBuffer(mac).append(File.separator).append(fileId).append(File.separator).append(folderName).append(File.separator).append("capture");
        StringBuffer sb = new StringBuffer(routeConfig.getHardDisk()).append(filePathBuffer.toString()).append(File.separator).append(fileName);

        boolean needUpload = false;
        File dbFile = new File(sb.toString());
        if (dbFile.exists()){
            String fileMD5 = FileMd5Util.getFileMD5(dbFile);
            if (md5.equals(fileMD5) && dbFile.length() == size){
                log.warn("文件已存在，MD5和文件大小一致。");

                SceneFileUpload uploadEntity = sceneFileUploadService.findByFileIdAndChunk(fileId, Integer.valueOf(chunk));
                if (uploadEntity != null){
                    uploadEntity.setSize((int) size);
                    uploadEntity.setMd5(md5);
                    uploadEntity.setFilePath(sb.toString());
                    uploadEntity.setFileSourceName(fileName);
                    uploadEntity.setUploadStatus(1);
                    sceneFileUploadService.updateById(uploadEntity);
                }else{
                    SceneFileUpload sceneFileUploadEntity = new SceneFileUpload();
                    sceneFileUploadEntity.setSize((int) size);
                    sceneFileUploadEntity.setMd5(md5);
                    sceneFileUploadEntity.setFilePath(sb.toString());
                    sceneFileUploadEntity.setFileSourceName(fileName);
                    sceneFileUploadEntity.setUploadStatus(1);
                    sceneFileUploadEntity.setFileId(fileId);
                    sceneFileUploadEntity.setChunk(Integer.valueOf(chunk));
                    sceneFileUploadService.save(sceneFileUploadEntity);
                }
                result = ResultData.ok();
            }else if (!md5.equals(fileMD5)) {
                log.warn("文件已上传，上传MD5："+md5+"，服务器MD5："+fileMD5+"。不一致。上传失败");
                FileUtil.delFile(sb.toString());
                needUpload = true;
            }else if (dbFile.length() != size){
                log.warn("文件已上传，文件大小不一致。上传失败");
                FileUtil.delFile(sb.toString());
                needUpload = true;
            }
        }else {
            log.warn("文件不存在，需要重新上传");
            needUpload = true;
        }

        // 4. 上传成功后，校验MD5和文件大小是否相等
        // 5. 如果相等，更新数据记录。如果不相等，返回上传失败结果。
        try {
            if (needUpload){
                String name = fileName.substring(0, fileName.lastIndexOf("."));
                String filePath = this.saveFile(file, filePathBuffer.toString(), name);
                File uploadFile = new File(filePath);
                String fileMD5 = FileMd5Util.getFileMD5(uploadFile);

                SceneFileUpload sceneFileUploadEntity = new SceneFileUpload();
                sceneFileUploadEntity.setSize((int) size);
                sceneFileUploadEntity.setMd5(md5);
                sceneFileUploadEntity.setFilePath(sb.toString());
                sceneFileUploadEntity.setFileSourceName(fileName);
                sceneFileUploadEntity.setFileId(fileId);
                sceneFileUploadEntity.setChunk(Integer.valueOf(chunk));

                if (md5.equals(fileMD5) && uploadFile.length() == size){
                    log.warn("文件已上传，MD5和文件大小一致。上传成功");
                    sceneFileUploadEntity.setUploadStatus(1);
                    sceneFileUploadService.save(sceneFileUploadEntity);
                    result = ResultData.ok();
                }else if (!md5.equals(fileMD5)) {
                    log.warn("文件已上传，上传MD5："+md5+"，服务器MD5："+fileMD5+"。不一致。上传失败");
                    sceneFileUploadEntity.setUploadStatus(-1);
                    sceneFileUploadService.save(sceneFileUploadEntity);
                    result = ResultData.error(ErrorCode.FAILURE_CODE_5052);
                }else if (uploadFile.length() != size){
                    log.warn("文件已上传，文件大小不一致。上传失败");
                    sceneFileUploadEntity.setUploadStatus(-1);
                    sceneFileUploadService.save(sceneFileUploadEntity);
                    result = ResultData.error(ErrorCode.FAILURE_CODE_5052);
                }
            }
        }catch (IllegalStateException | IOException e) {
            log.error(ErrorCode.FAILURE_CODE_5052.message(), e);
            result = ResultData.error(ErrorCode.FAILURE_CODE_5052);
        }
        return result;
    }

    @Override
    public ResultData uploadSuccess(String params) throws Exception {
        log.info("uploadSuccess-params: " + params);
        if (StrUtil.isEmpty(params)) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        params = params.replaceAll("%2B", "+");
        Base64 base64 = new Base64();
        String cipher = params;
        // 私钥解密过程
        byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile()),
                base64.decode(cipher));
        String restr = new String(res, "UTF-8");
        log.debug("uploadSuccess-params解密结果：" + restr);
        String[] strArr = restr.split(SPLICE);
        if (strArr.length != 3) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        String mac = strArr[0];
        String fileId = strArr[1];
        Object folderNameObject = redisUtil.get(fileId);
        String folderName = folderNameObject == null ? null : (String)folderNameObject;
        if(StringUtils.isEmpty(folderName)){
            SceneProPO scenePro = sceneProService.getSceneStatusByUnicode("/" + fileId + "/", TbStatus.VALID.code());
            if(scenePro != null){
                folderName = scenePro.getDataSource().substring(scenePro.getDataSource().lastIndexOf("/") + 1);
            }

            if(StringUtils.isEmpty(folderName)){
                SceneFileBuild sceneFileBuild = this.findByFileId(fileId);
                if(sceneFileBuild != null){
                    folderName = sceneFileBuild.getUnicode();
                }
            }
        }
        StringBuilder filePathBuffer = new StringBuilder(routeConfig.getHardDisk()).append(mac).append(File.separator).append(fileId).append(File.separator).append(folderName).append(File.separator).append("capture").append(File.separator);
        boolean flag = this.uploadSuccess(fileId, filePathBuffer);

        if(flag){
            //调用建模的方法
        }
        buildScene(filePathBuffer.toString(), fileId, false, null);
        return ResultData.ok();
    }

    @Override
    public ResultData uploadSuccessBuild(String params) throws Exception {
        log.info("uploadSuccessBuild-params: " + params);
        if (StringUtils.isEmpty(params)) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        params = params.replaceAll("%2B", "+");
        params = params.replaceAll(" ", "+");
        Base64 base64 = new Base64();
        String cipher = params;
        // 私钥解密过程
        byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile()),
                base64.decode(cipher));
        String restr = new String(res, "UTF-8");
        log.debug("uploadSuccessBuild-params解密结果：" + restr);
        String[] strArr = restr.split(SPLICE);
        if (strArr.length != 3) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        String mac = strArr[0];
        String fileId = strArr[1];
        Object folderNameObject = redisUtil.get(fileId);
        String folderName = folderNameObject == null ? null : (String)folderNameObject;
        if(StringUtils.isEmpty(folderName)){
            SceneProPO sceneProPO = sceneProService.getSceneStatusByUnicode("/" + fileId + "/", TbStatus.VALID.code());
            if(sceneProPO != null){
                folderName = sceneProPO.getDataSource().substring(sceneProPO.getDataSource().lastIndexOf("/") + 1);
            }

            if(StringUtils.isEmpty(folderName)){
                SceneFileBuild sceneFileBuild = this.findByFileId(fileId);
                if(sceneFileBuild != null){
                    folderName = sceneFileBuild.getUnicode();
                }
            }
        }
        StringBuilder filePathBuffer = new StringBuilder(routeConfig.getHardDisk())
                                    .append(mac).append(File.separator)
                                    .append(fileId).append(File.separator)
                                    .append(folderName).append(File.separator)
                                    .append("capture").append(File.separator);
        StringBuilder prefixBuffer = new StringBuilder(mac).append(File.separator).append(fileId).append(File.separator).append(folderName).append(File.separator);

        File filePath = new File(filePathBuffer.toString());
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        if("aws".equals(type)){
            CreateObjUtil.ossFileCp(ConstantFilePath.OSS_PREFIX + prefixBuffer.toString() + "data.fdage", filePathBuffer.toString() + "data.fdage");
        }else {
            CreateObjUtil.ossUtilCp(ConstantFilePath.OSS_PREFIX + prefixBuffer.toString() + "data.fdage", filePathBuffer.toString());
        }
        buildScene(filePathBuffer.toString(), fileId, true, prefixBuffer.toString());
        return ResultData.ok();
    }

    @Override
    public ResultData turntableUploadSuccess(String params) throws Exception {
        log.info("turntableUploadSuccess-params: " + params);
        if (StringUtils.isEmpty(params)) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        params = params.replaceAll("%2B", "+");
        params = params.replaceAll(" ", "+");
        Base64 base64 = new Base64();
        String cipher = params;
        // 私钥解密过程
        byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile()),
                base64.decode(cipher));
        String restr = new String(res, "UTF-8");
        log.info("uploadSuccessBuild-params解密结果：" + restr);
        String[] strArr = restr.split(SPLICE);
        if (strArr.length != 3) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        String mac = strArr[0];
        String fileId = strArr[1];
        Object folderNameObject = redisUtil.get(fileId);
        String folderName = folderNameObject == null ? null : (String)folderNameObject;
        if(StringUtils.isEmpty(folderName)){
            // TODO: 2022/3/19 plus版本稳定后删除----------------------------------------------------------------------start
//            SceneProPO sceneProPO = sceneProService.getSceneStatusByUnicode("/" + fileId + "/", TbStatus.VALID.code());
//            if(sceneProPO != null){
//                folderName = sceneProPO.getDataSource().substring(sceneProPO.getDataSource().lastIndexOf("/") + 1);
//            }
            // TODO: 2022/3/19 plus版本稳定后删除----------------------------------------------------------------------end
            ScenePlusExt scenePlusExt = scenePlusExtService.list(
                new LambdaQueryWrapper<ScenePlusExt>()
                    .like(ScenePlusExt::getDataSource, "%/" + fileId + "/%")).get(0);
            if(scenePlusExt != null){
                folderName = scenePlusExt.getDataSource().substring(scenePlusExt.getDataSource().lastIndexOf("/") + 1);
            }

            if(StringUtils.isEmpty(folderName)){
                SceneFileBuild sceneFileBuild = this.findByFileId(fileId);
                if(sceneFileBuild != null){
                    folderName = sceneFileBuild.getUnicode();
                }
            }
        }
        //判断 是否为激光相机
        ResultData<Camera> cameraResult = platformGoodsClient.getCameraByChildName(mac);
        if(!cameraResult.getSuccess()){
            log.error("获取不到Camera数据， childName: {}" ,  mac);
            throw new Exception();
        }
        Camera camera = cameraResult.getData();
        ResultData<CameraDetail> cameraDetailResult = platformGoodsClient.getCameraDetailByCameraId(camera.getId());
        if(!cameraDetailResult.getSuccess()){
            log.error("获取不到CameraDetail数据， CameraId: {}" ,  camera.getId());
            throw new Exception();
        }
        CameraDetail cameraDetail = cameraDetailResult.getData();

        String hardDisk = routeConfig.getHardDisk();
        if(cameraDetail!=null){
            if(cameraDetail.getCameraType() == 10){
                hardDisk = routeConfig.getHardDiskLaser();
            }
        }

        log.info("相机 mnt 路径 ： " + hardDisk + ", 相机类型 ： " + cameraDetail.getCameraType());

        //本机目录
        StringBuilder filePathBuffer = new StringBuilder(hardDisk).append(mac).append(File.separator).append(fileId).append(File.separator).append(folderName).append(File.separator).append("capture").append(File.separator);
        //云目录
        StringBuilder prefixBuffer = new StringBuilder(mac).append(File.separator).append(fileId).append(File.separator).append(folderName).append(File.separator);

        File filePath = new File(filePathBuffer.toString());
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        if("aws".equals(type)){
            CreateObjUtil.ossFileCp(ConstantFilePath.OSS_PREFIX + prefixBuffer.toString() + "data.fdage", filePathBuffer.toString() + "data.fdage");
        }else {
            CreateObjUtil.ossUtilCp(ConstantFilePath.OSS_PREFIX + prefixBuffer.toString() + "data.fdage", filePathBuffer.toString());
        }
        turntableBuildScene(filePathBuffer.toString(), fileId, true, prefixBuffer.toString());
        return ResultData.ok();
    }

    @Override
    public ResultData getS3UploadUrl(String params) throws Exception {
        if (StringUtils.isEmpty(params)) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        JSONObject jsonObject = JSON.parseObject(params);
        if(jsonObject == null){
            throw new BusinessException(ErrorCode.PARAM_FORMAT_ERROR);
        }
        JSONArray files = jsonObject.getJSONArray("Files");
        if(files == null){
            throw new BusinessException(ErrorCode.PARAM_FORMAT_ERROR);
        }
        List<String> urls = new ArrayList<>();
        for(int i = 0, len = files.size(); i < len; i++){
            urls.add(files.getJSONObject(i).getString("filename"));
        }
        return ResultData.ok(uploadToOssUtil.getUploadS3Url(urls));
    }

    @Override
    public ResultData buildLiteScene(String prefix, String dataFdage, String zipName, String userName, String password, String oldNum) throws Exception{
        log.info("参数-prefix: {}, dataFdage: {}, zipName: {}, password: {}, userName: {}", prefix,
                dataFdage, zipName, password, userName);

        if(StringUtils.isEmpty(prefix) || StringUtils.isEmpty(dataFdage) || StringUtils.isEmpty(zipName) ||
                StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }

        ResultData<Camera> cameraResult = platformGoodsClient.getCameraByChildName(userName);
        Camera camera = cameraResult.getData();

        if(camera == null){
            cameraResult = platformGoodsClient.getCameraBySnCode(userName);
            camera = cameraResult.getData();
        }
        if (camera == null){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        if(!password.equals(camera.getChildPassword())){
            throw new BusinessException(ErrorCode.FAILURE_CODE_3014);
        }
        CameraDetail cameraDetail = platformGoodsClient.getCameraDetailByCameraId(camera.getId()).getData();
        if(cameraDetail == null){
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        String unicode = prefix.substring(prefix.lastIndexOf("/") + 1);
        String path = ConstantFilePath.BUILD_MODEL_PATH + unicode;

        //下载data.fdage
        FileUtils.downLoadFromUrl(prefix + "/" + dataFdage + "?m=" + System.currentTimeMillis(), dataFdage, path + File.separator + "capture");
        String data = FileUtils.readFile(path + File.separator + "capture/" + dataFdage);
        JSONObject jsonObject = JSONObject.parseObject(data);
        if(jsonObject == null){
            log.info("data.fdage不存在");
            throw new BusinessException(CameraConstant.FAILURE_6009);
        }

        String sceneNum = "";
        //查看场景中的文件目录是否有改文件id，有则重新计算改场景，无则新建场景
        SceneProPO sceneProPO = sceneProService.findByFileId("/" + unicode);
        int rebuild = 1;
        if(StrUtil.isNotEmpty(oldNum)){
            sceneNum = oldNum;
        }else {

            if(sceneProPO != null){
                sceneNum = sceneProPO.getNum();
                //重算的场景，先移除该场景对应的容量
                sceneProService.rebuildReduceSpaceBySceneNum(sceneNum);
            }else {
                sceneNum = scene3dNumService.generateSceneNum(cameraDetail.getCameraType());
                rebuild = 0;
            }
        }

        String cameraName = jsonObject.getJSONObject("cam").getString("uuid");
        log.info("查询相机：" + cameraName);
        cameraResult = platformGoodsClient.getCameraByChildName(cameraName);
        camera = cameraResult.getData();

        if(camera ==  null){
            log.error("该相机不存在：" + cameraName);
            //偶现data.fdage给的相机码多了或少了4DKKPRO_
            if(cameraName.contains("4DKKPRO_")){
                cameraResult = platformGoodsClient.getCameraByChildName(cameraName.replace("4DKKPRO_", ""));
                camera = cameraResult.getData();
            }else {
                cameraResult = platformGoodsClient.getCameraByChildName("4DKKPRO_" + cameraName);
                camera = cameraResult.getData();
            }
            if(camera == null){
                throw new BusinessException(CameraConstant.FAILURE_6003);
            }
        }



        String icon = null;
        if(jsonObject.containsKey("icon") && StrUtil.isNotEmpty(jsonObject.getString("icon"))){
            //下载封面图icon
            FileUtils.downLoadFromUrl(prefix + "/" + jsonObject.getString("icon") + "?m=" + System.currentTimeMillis(), jsonObject.getString("icon"), path + File.separator + "capture");
            uploadToOssUtil.upload(path + File.separator + "capture" + File.separator +
                    jsonObject.getString("icon"), "images/images" + sceneNum + "/" + jsonObject.getString("icon"));
            icon = prefixAli + "images/images" + sceneNum + "/" + jsonObject.getString("icon");
            if("aws".equals(type)){
                icon = ConstantUrl.PREFIX_AWS + "images/images" + sceneNum + "/" + jsonObject.getString("icon");
            }
        }

        JSONObject firmwareVersion = new JSONObject();
        if(jsonObject.containsKey("camSoftwareVersion") && StrUtil.isNotEmpty(jsonObject.getString("camSoftwareVersion"))){
            firmwareVersion.put("camSoftwareVersion", jsonObject.getString("camSoftwareVersion"));
        }

        if(jsonObject.containsKey("version") && StrUtil.isNotEmpty(jsonObject.getString("version"))){
            firmwareVersion.put("version", jsonObject.getString("version"));
        }

        String sceneUrl = mainUrl + sceneProNewUrl;
        String buildType = "V3";
        //表示新款双目
        Long cameraType = 5L;
        if(jsonObject.getJSONObject("cam").getIntValue("type") == 5){

            //6表示小红屋双目
            cameraType = 6L;
        }

        // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------start
        SceneProPO scene = this.createScenePro(sceneNum, camera.getId(), camera.getChildName(), jsonObject.getString("creator"),
                jsonObject.getString("pwd"), unicode,
                cameraType, "", prefix, zipName, icon, "0", cameraDetail.getUserId(), userName,
                jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                jsonObject.getJSONArray("points").size(), jsonObject.getString("name"), jsonObject.getString("info"),
                jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
                4, firmwareVersion.toString(), sceneUrl, buildType, type, ecsType, cameraDetail.getCooperationUser());
        // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------end

        Object[] objects = this.createScenePlus2(sceneNum, camera.getId(), camera.getChildName(),
            jsonObject.getString("creator"),
            jsonObject.getString("pwd"), unicode,
            cameraType, "", prefix, zipName, icon, "0", cameraDetail.getUserId(), userName,
            jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location"))
                ? "sfm" : "slam",
            jsonObject.getJSONArray("points").size(), jsonObject.getString("name"),
            jsonObject.getString("info"),
            jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
            4, firmwareVersion.toString(), sceneUrl, buildType, ecsType,
            cameraDetail.getCooperationUser());
        BuildSceneCallMessage mqMessage = (BuildSceneCallMessage)objects[1];

        if(scene == null){
            log.info("双目相机入库失败");
            return ResultData.error(ErrorCode.FAILURE_CODE_5056);
        }
        JSONObject statusJson = new JSONObject();
        //临时将-2改成1，app还没完全更新
        statusJson.put("status", scene.getSceneStatus() == -2? 1 : scene.getSceneStatus());
        statusJson.put("webSite", scene.getWebSite());
        statusJson.put("sceneNum", scene.getNum());
        statusJson.put("thumb", scene.getThumb());
        statusJson.put("payStatus", scene.getPayStatus());
        FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data/data"+sceneNum+File.separator+"status.json", statusJson.toString());
        uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH+"data/data"+sceneNum+File.separator+"status.json",
                "data/data"+sceneNum+File.separator+"status.json");

        //删除oss的houst_floor.json
        uploadToOssUtil.delete("data/data"+sceneNum+File.separator+"houst_floor.json");

        rabbitMqProducer.sendByWorkQueue(queueModelingPre, mqMessage);

        Map<String, String> map = new HashMap<>();
        map.put("sceneNum", sceneNum);
        map.put("sceneUrl", sceneUrl + sceneNum);
        return ResultData.ok(map);


    }

    @Override
    public ResultData buildScene(String prefix, String unicode, String zip, String dataFdage) throws Exception{

        String data = FileUtils.readFile(ConstantFilePath.BUILD_MODEL_PATH + unicode + "/data.fdage");
        JSONObject jsonObject = JSONObject.parseObject(data);
        String cameraName = jsonObject.getJSONObject("cam").getString("uuid");

        log.info("查询相机：" + cameraName);
        Camera cameraEntity = platformGoodsClient.getCameraByChildName(cameraName).getData();
        if(cameraEntity ==  null){
            log.error("该相机不存在：" + cameraName);
            //偶现data.fdage给的相机码多了或少了4DKKPRO_
            if(cameraName.contains("4DKKPRO_")){
                cameraEntity = platformGoodsClient.getCameraByChildName(cameraName.replace("4DKKPRO_", "")).getData();
            }else {
                cameraEntity = platformGoodsClient.getCameraByChildName("4DKKPRO_" + cameraName).getData();
            }
            if(cameraEntity == null){
                throw new BusinessException(CameraConstant.FAILURE_6003);
            }
        }
        CameraDetail detailEntity = platformGoodsClient.getCameraDetailByCameraId(cameraEntity.getId()).getData();
        if(detailEntity ==  null){
            log.error("该相机详情不存在：" + cameraName);
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        String sceneNum = scene3dNumService.generateSceneNum(detailEntity.getCameraType());

        return ResultData.ok(mainUrl + sceneProNewUrl + sceneNum);
    }

    public void turntableBuildScene(String filePath, String fileId, boolean fromOss, String prefix) throws Exception{
        
        String data = FileUtils.readFile(filePath + "data.fdage");
        JSONObject jsonObject = JSONObject.parseObject(data);

        //调用createScene方法生成scene数据和加入算法队列
        if(jsonObject == null) {
            log.info("data.fdage文件不存在");
            throw new BusinessException(CameraConstant.FAILURE_6009);
        }

        String sceneNum = "";
        String snCode = jsonObject.getJSONObject("cam").getString("uuid");
        String unicode = jsonObject.getString("creator") + "_" + jsonObject.getString("uuidtime"); //从data.fage 取出
        //查看场景中的文件目录是否有改文件id，有则重新计算改场景，无则新建场景
        ScenePlusExt scenePlusExt = scenePlusExtService.list(
            new LambdaQueryWrapper<ScenePlusExt>()
                .like(ScenePlusExt::getDataSource, "%/" + fileId + "/%")).get(0);
        ScenePlus scene1 = null;
        if(Objects.nonNull(scenePlusExt)){
            scene1 = scenePlusService.getById(scenePlusExt.getPlusId());
        }

        // TODO: 2022/3/19 plus 版本稳定后删除-------------------------------start
//        SceneProPO scene = sceneProService.findByFileId("/" + fileId + "/");
        // TODO: 2022/3/19 plus 版本稳定后删除-------------------------------end

        int rebuild = 1;
        log.info("是否是重算，rebuild：{}",rebuild);

        log.info("查询相机：" + snCode);
        ResultData<Camera> cameraResult = platformGoodsClient.getCameraByChildName(snCode);
        Camera camera = cameraResult.getData();

        if(camera ==  null){
            log.error("该相机不存在：" + snCode);
            cameraResult = platformGoodsClient.getCameraBySnCode(snCode);
            camera = cameraResult.getData();
            if(camera == null){
                throw new BusinessException(CameraConstant.FAILURE_6003);
            }
        }

        ResultData<CameraDetail> cameraDetailResult = platformGoodsClient.getCameraDetailByCameraId(camera.getId());
        CameraDetail cameraDetail = cameraDetailResult.getData();
        if(cameraDetail ==  null){
            log.error("该相机详情不存在：" + snCode);
            throw new BusinessException(CameraConstant.FAILURE_6003);
        }
        if(scene1 != null){
            sceneNum = scene1.getNum();
            if(scene1.getSceneStatus() == SceneStatus.wait.code()){
                log.info(sceneNum + ":场景处于计算中，不能再计算");
                return;
            }
        }else {
            sceneNum = scene3dNumService.generateSceneNum(cameraDetail.getCameraType());
            rebuild = 0;
        }
        if(sceneNum == null){
            log.error("大场景序号为空：" + sceneNum);
            throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
        }

        String imageViewPath = String.format(UploadFilePath.IMG_VIEW_PATH, sceneNum);
        String dataViewPath = String.format(UploadFilePath.DATA_VIEW_PATH, sceneNum);

        String userName = null;
        if(cameraDetail.getUserId() != null){
            ResultData<SSOUser> ssoResult = platformUserClient.getSSOUserByUserId(cameraDetail.getUserId());
            SSOUser user = ssoResult.getData();
            if(user != null){
                userName = user.getUserName();
            }
        }

        String icon = null;
        if(jsonObject.containsKey("icon") && StrUtil.isNotEmpty(jsonObject.getString("icon"))){
            CreateObjUtil.ossUtilCp(ConstantFilePath.OSS_PREFIX + prefix + jsonObject.getString("icon"), filePath);
            icon = prefixAli + imageViewPath + jsonObject.getString("icon");
            if("aws".equals(type)){
                CreateObjUtil.ossFileCp(ConstantFilePath.OSS_PREFIX + prefix + jsonObject.getString("icon"), filePath + jsonObject.getString("icon"));
                icon = ConstantUrl.PREFIX_AWS + imageViewPath + jsonObject.getString("icon");
            }
            uploadToOssUtil.upload(filePath + jsonObject.getString("icon"), imageViewPath + jsonObject.getString("icon"));

            // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
            uploadToOssUtil.upload(filePath + jsonObject.getString("icon"), "images/images" + sceneNum + "/" + jsonObject.getString("icon"));

            log.info("上传icon成功....");
        }

        JSONObject firmwareVersion = new JSONObject();
        if(jsonObject.containsKey("camSoftwareVersion") && StrUtil.isNotEmpty(jsonObject.getString("camSoftwareVersion"))){
            firmwareVersion.put("camSoftwareVersion", jsonObject.getString("camSoftwareVersion"));
        }

        if(jsonObject.containsKey("version") && StrUtil.isNotEmpty(jsonObject.getString("version"))){
            firmwareVersion.put("version", jsonObject.getString("version"));
        }

        String sceneUrl = mainUrl + sceneProNewUrl;
        String buildType = "V3";
        //13表示转台
        Long cameraType = 13L;

        //激光转台 八目相机占用 10 和 11
        if(jsonObject.getJSONObject("cam").getIntValue("type") == 10){
            //激光转台
            cameraType = 14L;
        }

        //重算的场景，先移除该场景对应的容量
        if(rebuild == 1){
            scenePlusService.resetSpace(sceneNum);
            // TODO: 2022/3/19 plus版本稳定后需要删除---------------start
            sceneProService.rebuildReduceSpaceBySceneNum(sceneNum);
            // TODO: 2022/3/19 plus版本稳定后需要删除---------------end
        }else {
            //上传log-main.png
            uploadToOssUtil.upload(ConstantFilePath.LOGO_PATH + "logo-main.png", imageViewPath + "logo-main.png");
            uploadToOssUtil.upload(ConstantFilePath.LOGO_PATH + "logo-main-en.png", imageViewPath + "logo-main-en.png");
            // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
            uploadToOssUtil.upload(ConstantFilePath.LOGO_PATH + "logo-main.png", "images/images" + sceneNum + "/logo-main.png");
            uploadToOssUtil.upload(ConstantFilePath.LOGO_PATH + "logo-main-en.png", "images/images" + sceneNum + "/logo-main-en.png");

            log.info("第一次计算场景,上传logo-main.png");

        }
        SceneProPO scene = null;
        // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------start
        scene = this.createScenePro(sceneNum, camera.getId(), camera.getChildName(), jsonObject.getString("creator"),
                jsonObject.getString("pwd"), unicode,
                cameraType, String.valueOf(fileId), prefix, "", icon, "0", cameraDetail.getUserId(), userName,
                jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                jsonObject.getJSONArray("points").size(), jsonObject.getString("name"), jsonObject.getString("info"),
                jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
                jsonObject.getInteger("resolution"), firmwareVersion.toString(), sceneUrl, buildType, type, ecsType, cameraDetail.getCooperationUser());
        // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------end

        Object[] objects = this.createScenePlus2(sceneNum, camera.getId(), camera.getChildName(), jsonObject.getString("creator"),
            jsonObject.getString("pwd"), unicode,
            cameraType, String.valueOf(fileId), prefix, "", icon, "0", cameraDetail.getUserId(), userName,
            jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
            jsonObject.getJSONArray("points").size(), jsonObject.getString("name"), jsonObject.getString("info"),
            jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
            jsonObject.getInteger("resolution"), firmwareVersion.toString(), sceneUrl, buildType, ecsType, cameraDetail.getCooperationUser());
        BuildSceneCallMessage  mqMessage = (BuildSceneCallMessage)objects[1];

        if(scene != null){
            JSONObject statusJson = new JSONObject();
            //临时将-2改成1，app还没完全更新
            statusJson.put("status", scene.getSceneStatus() == -2? 1 : scene.getSceneStatus());
            statusJson.put("webSite", scene.getWebSite());
            statusJson.put("sceneNum", scene.getNum());
            statusJson.put("thumb", scene.getThumb());
            statusJson.put("payStatus", scene.getPayStatus());
            statusJson.put("recStatus", scene.getRecStatus());
            FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data/data"+sceneNum+File.separator+"status.json", statusJson.toString());

            uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH+"data/data"+sceneNum+File.separator+"status.json",
                    dataViewPath + File.separator+"status.json");

            // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
            uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH+"data/data"+sceneNum+File.separator+"status.json",
                    "data/data"+sceneNum+File.separator+"status.json");

            log.info("上传status.json,上传内容：{}" + statusJson.toString());
        }

        if(cameraDetail.getCompanyId() != null){

            ResultData<Company> companyResult = platformUserClient.getCompanyById(cameraDetail.getCompanyId());
            Company company = companyResult.getData();
            if(company != null){

                Map<String, Object> jsonMap = new HashMap<>();

                log.info("复制企业logo");
                SceneProEdit sceneProEdit = sceneProEditService.findByProId(scene.getId());
                SceneProEditExt sceneProEditExt = sceneProEditExtService.getByProEditId(sceneProEdit.getId());

                if(StrUtil.isNotEmpty(company.getTopLogo())){

                    FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getTopLogo(),
                            ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/logo-main.png", true);

                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/logo-main.png",
                            imageViewPath + "logo-main.png");

                    // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/logo-main.png",
                            "images/images" + sceneNum + "/logo-main.png");

                }

                if(StrUtil.isNotEmpty(company.getFloorLogo())){

                    FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getFloorLogo(),
                            ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/floorLogoImg.png", true);

                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/floorLogoImg.png",
                            imageViewPath + "floorLogoImg.png");

                    // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/floorLogoImg.png",
                            "images/images" + sceneNum + "/floorLogoImg.png");

                    sceneProEdit.setFloorLogo("user");
                    jsonMap.put("floorLogoSize", sceneProEdit.getFloorLogoSize());
                    jsonMap.put("floorLogo", "user");
                }

                if(StrUtil.isNotEmpty(company.getQrLogo())){

                    FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getQrLogo(),
                            ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png", true);

                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png",
                            imageViewPath + "QRShareLogo.png");

                    // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png",
                            "images/images" + sceneNum + "/QRShareLogo.png");

//                    sceneProEdit.setShareLogo("images/images" + sceneNum + "/QRShareLogo.png");//旧系统代码，先保留
                    sceneProEdit.setShareLogo(imageViewPath + "QRShareLogo.png");

                    //生成新的分享的二维码-中文版本
                    MatrixToImageWriterUtil.createQRCode(sceneUrl + sceneNum, ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+sceneNum+".png",
                        false, ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png");
                    //生成新的分享的二维码-英文版本
                    MatrixToImageWriterUtil.createQRCode(sceneUrl + sceneNum + "&lang=en", ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+sceneNum+"_en.png",
                        false,  ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png");
                }

                if(StrUtil.isNotEmpty(company.getMarkerLogo())){
                    FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getMarkerLogo(),
                            ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/marker.png", true);
                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/marker.png",
                            imageViewPath + "marker.png");

                    // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/marker.png",
                            "images/images" + sceneNum + "/marker.png");

                    sceneProEdit.setMarkerLogo("user");
                    jsonMap.put("markerLogo", "user");
                }

                sceneProEdit.setUpdateTime(Calendar.getInstance().getTime());
                sceneProEditService.updateById(sceneProEdit);

                sceneProEditExt.setUpdateTime(Calendar.getInstance().getTime());
                sceneProEditExt.setShowLogoBottom(company.getShowLogo());
                sceneProEditExtService.updateById(sceneProEditExt);

                jsonMap.put("showLogoBottom", company.getShowLogo());
                FileUtils.writeJsonFile(ConstantFilePath.SCENE_PATH + "data/data" + sceneNum + "/scene.json", jsonMap);
            }

            //删除oss的houst_floor.json
            uploadToOssUtil.delete(dataViewPath + "houst_floor.json");

            // TODO: 2022/1/24 暂时保留旧版本，系统稳定后删除
            uploadToOssUtil.delete("data/data"+sceneNum+File.separator+"houst_floor.json");

        }

        //激光转台 八目相机占用 10 和 11
        log.info("发送mq，camType:{}", jsonObject.getJSONObject("cam").getIntValue("type"));
        if(jsonObject.getJSONObject("cam").getIntValue("type") == 10){
//            mqProducer.sendOneWay(topicLaserA, mqMessage);
            // TODO: 2022/3/19 这里应该是发送激光的 ，目前还不清楚，先统一发送同一个mq
            rabbitMqProducer.sendByWorkQueue(queueModelingPre, mqMessage);
        }else if(scene != null){
//            mqProducer.sendInOrder(topicModelingA, scene.getId()+"", scene.getMqMsg());
            rabbitMqProducer.sendByWorkQueue(queueModelingPre, mqMessage);
        }
    }


    @Override
    public ResultData buildScene(BuildSceneParamVO buildScene) throws Exception {
        if(StrUtil.isEmpty(buildScene.getUnicode()) || StrUtil.isEmpty(buildScene.getCameraName()) ||
                StrUtil.isEmpty(buildScene.getSceneKey()) ||
                StrUtil.isEmpty(buildScene.getPrefix()) || StrUtil.isEmpty(buildScene.getFileName()) ||
                StrUtil.isEmpty(buildScene.getSceneName()) || StrUtil.isEmpty(buildScene.getSceneDec()) ||
                buildScene.getSceneType() == null || buildScene.getShootCount() == null ||
                StrUtil.isEmpty(buildScene.getThumb()) || StrUtil.isEmpty(buildScene.getAlgorithm()) ){
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }
        String sceneNum = null;
        try{

            log.info("查询相机：" + buildScene.getCameraName());
            ResultData<Camera> cameraResult= platformGoodsClient.getCameraByChildName(buildScene.getCameraName());
            Camera camera = cameraResult.getData();

            if(camera ==  null){
                log.error("该相机不存在：" + buildScene.getCameraName());
                throw new BusinessException(CameraConstant.FAILURE_6003);
            }

            ResultData<CameraDetail> cameraDetailResult = platformGoodsClient.getCameraDetailByCameraId(camera.getId());
            CameraDetail cameraDetail = cameraDetailResult.getData();

            sceneNum = scene3dNumService.generateSceneNum(cameraDetail.getCameraType());
            if(sceneNum == null){
                log.error("大场景序号为空：" + sceneNum);
                throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
            }
            int balance = Integer.valueOf(cameraDetail.getBalance());
            if(balance - Constant.MONEY_SCENE <0){
                log.error("相机点数不足：" + buildScene.getCameraName());
                throw new BusinessException(CameraConstant.FAILURE_6006);
            }

            ResultData<SSOUser> ssoUserResult = platformUserClient.getSSOUserByUserId(cameraDetail.getUserId());
            SSOUser user = ssoUserResult.getData();
            if(user == null){
                log.error("用户id不存在：" + cameraDetail.getUserId());
                throw new BusinessException(ErrorCode.FAILURE_CODE_3015);
            }
            ScenePO scenePO = this.createScene(sceneNum, camera.getId(), camera.getChildName(), buildScene.getPhoneId(),
                    buildScene.getSceneKey(), buildScene.getUnicode(), cameraDetail.getCameraType(), "0", buildScene.getPrefix(),
                    buildScene.getFileName(), buildScene.getThumb(), "0", cameraDetail.getUserId(), user.getUserName(),
                    buildScene.getAlgorithm(), buildScene.getShootCount(), buildScene.getSceneName(),
                    buildScene.getSceneDec(), buildScene.getSceneType(), buildScene.getGps(), 0, mainUrl + sceneUrl, ecsType);

            return ResultData.ok(scenePO);
        }catch (Exception e){
            log.error("增加大场景失败：" + sceneNum);
            sceneProService.updateStatus(sceneNum, -1);
            throw new BusinessException(ErrorCode.FAILURE_CODE_5011);
        }
    }

    public void buildScene(String filePath, String fileId, boolean fromOss, String prefix) throws Exception{
        //获取解压后的资源的data.fdage中的数据
        String data = FileUtils.readFile(filePath + "data.fdage");
        JSONObject jsonObject = JSONObject.parseObject(data);

        //调用createScene方法生成scene数据和加入算法队列
        if(jsonObject != null){
            //有calibration值为标定，1: camera_calibration 2: color_anlysis，0正常计算
            if(jsonObject.get("calibration") != null && jsonObject.getString("calibration").equals("1")){
                String mac = filePath.replace(ConstantFilePath.BUILD_MODEL_PATH, "").split("/")[0];
                String calPath = ConstantFilePath.BUILD_MODEL_PATH + mac + "/camera_calibration";
                //生成标定数据
                ComputerUtil.createCalibrationData(calPath, filePath);
                //开始标定计算
                rabbitMqProducer.sendByWorkQueue(queueModelingCall, calPath);


            }else if(jsonObject.get("calibration") != null && jsonObject.getString("calibration").equals("2")){
                String mac = filePath.replace(ConstantFilePath.BUILD_MODEL_PATH, "").split("/")[0];
                String calPath = ConstantFilePath.BUILD_MODEL_PATH + mac + "/color_anlysis";
                //生成标定数据
                ComputerUtil.createCalibrationData(calPath, filePath);
                //开始标定计算
                Map<String,String> map = ComputerUtil.computerCalibration(calPath);
            }else if(jsonObject.get("calibration") != null && jsonObject.getString("calibration").equals("3")){
                String mac = filePath.replace(ConstantFilePath.BUILD_MODEL_PATH, "").split("/")[0];
                String calPath = ConstantFilePath.BUILD_MODEL_PATH + mac + "/shading";
                //生成标定数据
                ComputerUtil.createCalibrationData(calPath, filePath);
                //开始标定计算
                rabbitMqProducer.sendByWorkQueue(queueModelingCall, calPath);
            }else {

                String sceneNum = "";

                String cameraName = jsonObject.getJSONObject("cam").getString("uuid");
                String unicode = jsonObject.getString("creator") + "_" + jsonObject.getString("uuidtime");

                log.info("查询相机：" + cameraName);
                ResultData<Camera> cameraResult = platformGoodsClient.getCameraByChildName(cameraName);
                Camera camera = cameraResult.getData();

                if(camera ==  null){
                    log.error("该相机不存在：" + cameraName);
                    //偶现data.fdage给的相机码多了或少了4DKKPRO_
                    if(cameraName.contains("4DKKPRO_")){
                        cameraResult = platformGoodsClient.getCameraByChildName(cameraName.replace("4DKKPRO_", ""));
                        camera = cameraResult.getData();
                    }else {
                        cameraResult = platformGoodsClient.getCameraByChildName("4DKKPRO_" + cameraName);
                        camera = cameraResult.getData();
                    }
                    if(camera == null){
                        throw new BusinessException(CameraConstant.FAILURE_6003);
                    }
                }

                ResultData<CameraDetail> cameraDetailResult = platformGoodsClient.getCameraDetailByCameraId(camera.getId());
                CameraDetail cameraDetail = cameraDetailResult.getData();
                if(cameraDetail ==  null){
                    log.error("该相机详情不存在：" + cameraName);
                    throw new BusinessException(CameraConstant.FAILURE_6003);
                }

                //查看场景中的文件目录是否有改文件id，有则重新计算改场景，无则新建场景
                SceneProPO proEntity = sceneProService.findByFileId("/" + fileId + "/");
                int rebuild = 1;
                if(proEntity != null){
                    sceneNum = proEntity.getNum();
                    if(proEntity.getSceneStatus() == SceneStatus.wait.code()){
                        log.info(sceneNum + ":场景处于计算中，不能再计算");
                        return;
                    }
                }else {
                    sceneNum = scene3dNumService.generateSceneNum(cameraDetail.getCameraType());
                    rebuild = 0;
                }

                if(sceneNum == null){
                    log.error("大场景序号为空：" + sceneNum);
                    throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
                }



                String userName = null;
                if(cameraDetail.getUserId() != null){
                    ResultData<SSOUser> ssoResult = platformUserClient.getSSOUserByUserId(cameraDetail.getUserId());
                    SSOUser user = ssoResult.getData();
                    if(user != null){
                        userName = user.getUserName();
                    }
                }
                String icon = null;
                if(jsonObject.containsKey("icon") && StrUtil.isNotEmpty(jsonObject.getString("icon"))){
                    CreateObjUtil.ossUtilCp(ConstantFilePath.OSS_PREFIX + prefix + jsonObject.getString("icon"), filePath);
                    icon = prefixAli + "images/images" + sceneNum + "/" + jsonObject.getString("icon");
                    if("aws".equals(type)){
                        CreateObjUtil.ossFileCp(ConstantFilePath.OSS_PREFIX + prefix + jsonObject.getString("icon"), filePath + jsonObject.getString("icon"));
                        icon = ConstantUrl.PREFIX_AWS + "images/images" + sceneNum + "/" + jsonObject.getString("icon");
                    }
                    uploadToOssUtil.upload(filePath + jsonObject.getString("icon"), "images/images" + sceneNum + "/" + jsonObject.getString("icon"));
                }

                JSONObject firmwareVersion = new JSONObject();
                if(jsonObject.containsKey("camSoftwareVersion") && StrUtil.isNotEmpty(jsonObject.getString("camSoftwareVersion"))){
                    firmwareVersion.put("camSoftwareVersion", jsonObject.getString("camSoftwareVersion"));
                }

                if(jsonObject.containsKey("version") && StrUtil.isNotEmpty(jsonObject.getString("version"))){
                    firmwareVersion.put("version", jsonObject.getString("version"));
                }

                String sceneUrl = mainUrl + sceneProUrl;
                String buildType = "V2";
                Long cameraType = 10L;
                //根据videoVersion判断是V2还是V3版本的算法和页面
                if(jsonObject.containsKey("videoVersion") && StrUtil.isNotEmpty(jsonObject.getString("videoVersion"))){
                    if(jsonObject.getIntValue("videoVersion") >= 4){
                        buildType = "V3";
                        cameraType = 11L;
                        sceneUrl = mainUrl + sceneProNewUrl;
                    }
                }
                //重算的场景，先移除该场景对应的容量
                if(rebuild == 1){
                    sceneProService.rebuildReduceSpaceBySceneNum(sceneNum);
                }else {
                    //上传log-main.png
                    uploadToOssUtil.upload(ConstantFilePath.LOGO_PATH + "logo-main.png", "images/images" + sceneNum + "/logo-main.png");
                    uploadToOssUtil.upload(ConstantFilePath.LOGO_PATH + "logo-main-en.png", "images/images" + sceneNum + "/logo-main-en.png");
                }
                SceneProPO sceneProPO = null;
                Object[] objects = null;
                BuildSceneCallMessage mqMessage = null;
                if(fromOss){
                    // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------start
                    sceneProPO = this.createScenePro(sceneNum, camera.getId(), camera.getChildName(), jsonObject.getString("creator"),
                            jsonObject.getString("pwd"), unicode,
                            cameraType, String.valueOf(fileId), prefix, "", icon, "0", cameraDetail.getUserId(), userName,
                            jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                            jsonObject.getJSONArray("points").size(), jsonObject.getString("name"), jsonObject.getString("info"),
                            jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
                            jsonObject.getInteger("resolution"), firmwareVersion.toString(), sceneUrl, buildType, type, ecsType,cameraDetail.getCooperationUser());
                    // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------end

                    objects = this.createScenePlus2(sceneNum, camera.getId(), camera.getChildName(), jsonObject.getString("creator"),
                        jsonObject.getString("pwd"), unicode,
                        cameraType, String.valueOf(fileId), prefix, "", icon, "0", cameraDetail.getUserId(), userName,
                        jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                        jsonObject.getJSONArray("points").size(), jsonObject.getString("name"), jsonObject.getString("info"),
                        jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
                        jsonObject.getInteger("resolution"), firmwareVersion.toString(), sceneUrl, buildType, ecsType,cameraDetail.getCooperationUser());

                }else {
                    // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------start
                    sceneProPO = this.createScenePro(sceneNum, camera.getId(), camera.getChildName(), jsonObject.getString("creator"),
                            jsonObject.getString("pwd"), unicode,
                            cameraDetail.getGoodsId(), String.valueOf(fileId), "", "", icon, "0", cameraDetail.getUserId(), userName,
                            jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                            jsonObject.getJSONArray("points").size(), jsonObject.getString("name"), jsonObject.getString("info"),
                            jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
                            jsonObject.getInteger("resolution"), firmwareVersion.toString(), sceneUrl, buildType, type, ecsType, cameraDetail.getCooperationUser());
                    // TODO: 2022/3/21 plus版本稳定后删除 ---------------------------------------------------------------------------------end

                    objects = this.createScenePlus2(sceneNum, camera.getId(), camera.getChildName(), jsonObject.getString("creator"),
                        jsonObject.getString("pwd"), unicode,
                        cameraDetail.getGoodsId(), String.valueOf(fileId), "", "", icon, "0", cameraDetail.getUserId(), userName,
                        jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                        jsonObject.getJSONArray("points").size(), jsonObject.getString("name"), jsonObject.getString("info"),
                        jsonObject.getInteger("scenetype"), jsonObject.getString("gps"), rebuild,
                        jsonObject.getInteger("resolution"), firmwareVersion.toString(), sceneUrl, buildType, ecsType, cameraDetail.getCooperationUser());
                }
                mqMessage = (BuildSceneCallMessage)objects[1];

                if(sceneProPO != null){
                    JSONObject statusJson = new JSONObject();
                    //临时将-2改成1，app还没完全更新
                    statusJson.put("status", sceneProPO.getSceneStatus() == -2 ? 1 : sceneProPO.getSceneStatus());
                    statusJson.put("webSite", sceneProPO.getWebSite());
                    statusJson.put("sceneNum", sceneProPO.getNum());
                    statusJson.put("thumb", sceneProPO.getThumb());
                    statusJson.put("payStatus", sceneProPO.getPayStatus());
                    statusJson.put("recStatus", sceneProPO.getRecStatus());
                    FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data/data"+sceneNum+File.separator+"status.json", statusJson.toString());
                    uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH+"data/data"+sceneNum+File.separator+"status.json",
                            "data/data"+sceneNum+File.separator+"status.json");
                }

                //删除oss的houst_floor.json(国际版可能会卡住)
                uploadToOssUtil.delete("data/data"+sceneNum+File.separator+"houst_floor.json");

                if(cameraDetail.getCompanyId() != null){
                    ResultData<Company> companyResult = platformUserClient.getCompanyById(cameraDetail.getCompanyId());
                    Company company = companyResult.getData();
                    if(company != null){

                        Map<String, Object> jsonMap = new HashMap<>();

                        log.info("复制企业logo");
                        SceneProEdit sceneProEdit = sceneProEditService.findByProId(sceneProPO.getId());
                        SceneProEditExt sceneProEditExt = sceneProEditExtService.getByProEditId(sceneProEdit.getId());

                        if(StrUtil.isNotEmpty(company.getTopLogo())){
                            //复制阿里云主服务器的图片到横琴云副服务器中
                            if(!new File(ConstantFilePath.BASE_PATH + File.separator + company.getTopLogo()).exists()){
                                log.info("下载topLogo");
                                FileUtils.downLoadFromUrl(mainUrl + company.getTopLogo() + "?t=" + System.currentTimeMillis(),
                                        company.getTopLogo().substring(company.getTopLogo().lastIndexOf("/") + 1),
                                        ConstantFilePath.BASE_PATH + company.getTopLogo().substring(0, company.getTopLogo().lastIndexOf("/")));
                            }

                            FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getTopLogo(),
                                    ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/logo-main.png", true);
                            uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/logo-main.png",
                                    "images/images" + sceneNum + "/logo-main.png");
                        }

                        if(StrUtil.isNotEmpty(company.getFloorLogo())){
                            //复制阿里云主服务器的图片到横琴云副服务器中
                            if(!new File(ConstantFilePath.BASE_PATH + File.separator + company.getFloorLogo()).exists()){
                                log.info("下载floorLogo");
                                FileUtils.downLoadFromUrl(mainUrl + company.getFloorLogo() + "?t=" + System.currentTimeMillis(),
                                        company.getFloorLogo().substring(company.getFloorLogo().lastIndexOf("/") + 1),
                                        ConstantFilePath.BASE_PATH + company.getFloorLogo().substring(0, company.getFloorLogo().lastIndexOf("/")));
                            }

                            FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getFloorLogo(),
                                    ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/floorLogoImg.png", true);
                            uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/floorLogoImg.png",
                                    "images/images" + sceneNum + "/floorLogoImg.png");

                            sceneProEdit.setFloorLogo("user");
                            jsonMap.put("floorLogoSize", sceneProEdit.getFloorLogoSize());
                            jsonMap.put("floorLogo", "user");
                        }

                        if(StrUtil.isNotEmpty(company.getQrLogo())){
                            //复制阿里云主服务器的图片到横琴云副服务器中
                            if(!new File(ConstantFilePath.BASE_PATH + File.separator + company.getQrLogo()).exists()){
                                log.info("下载qrLogo");
                                FileUtils.downLoadFromUrl(mainUrl + company.getQrLogo() + "?t=" + System.currentTimeMillis(),
                                        company.getQrLogo().substring(company.getQrLogo().lastIndexOf("/") + 1),
                                        ConstantFilePath.BASE_PATH + company.getQrLogo().substring(0, company.getQrLogo().lastIndexOf("/")));
                            }

                            FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getQrLogo(),
                                    ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png", true);
                            uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png",
                                    "images/images" + sceneNum + "/QRShareLogo.png");
                            sceneProEdit.setShareLogo("images/images" + sceneNum + "/QRShareLogo.png");

                            //生成新的分享的二维码
                            MatrixToImageWriterUtil.createQRCode(sceneUrl + sceneNum, ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+sceneNum+".png",
                                false, ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png");
                            MatrixToImageWriterUtil.createQRCode(sceneUrl + sceneNum + "&lang=en", ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+sceneNum+"_en.png",
                                false,  ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/QRShareLogo.png");
                        }

                        if(StrUtil.isNotEmpty(company.getMarkerLogo())){
                            //复制阿里云主服务器的图片到横琴云副服务器中
                            if(!new File(ConstantFilePath.BASE_PATH + File.separator + company.getMarkerLogo()).exists()){
                                log.info("下载floorLogo");
                                FileUtils.downLoadFromUrl(mainUrl + company.getMarkerLogo() + "?t=" + System.currentTimeMillis(),
                                        company.getMarkerLogo().substring(company.getMarkerLogo().lastIndexOf("/") + 1),
                                        ConstantFilePath.BASE_PATH + company.getMarkerLogo().substring(0, company.getMarkerLogo().lastIndexOf("/")));
                            }

                            FileUtils.copyFile(ConstantFilePath.BASE_PATH + File.separator + company.getMarkerLogo(),
                                    ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/marker.png", true);
                            uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "images/images" + sceneNum + "/marker.png",
                                    "images/images" + sceneNum + "/marker.png");

                            sceneProEdit.setMarkerLogo("user");
                            jsonMap.put("markerLogo", "user");
                        }

                        sceneProEdit.setUpdateTime(Calendar.getInstance().getTime());
                        sceneProEditService.updateById(sceneProEdit);

                        sceneProEditExt.setUpdateTime(Calendar.getInstance().getTime());
                        sceneProEditExt.setShowLogoBottom(company.getShowLogo());
                        sceneProEditExtService.updateById(sceneProEditExt);

                        jsonMap.put("showLogoBottom", company.getShowLogo());
                        FileUtils.writeJsonFile(ConstantFilePath.SCENE_PATH + "data/data" + sceneNum + "/scene.json", jsonMap);
                    }

                }

                // 正顺相机不予计算
                Long companyId = cameraDetail.getCompanyId();
                if(Objects.nonNull(unCalculatedCompanyIds) && Arrays.asList(unCalculatedCompanyIds).contains(companyId)){
                    return;
                }
                if(sceneProPO != null){
                    rabbitMqProducer.sendByWorkQueue(queueModelingPre,  mqMessage);
                }

            }
        }else {
            log.info("data.fdage文件不存在");
            throw new BusinessException(CameraConstant.FAILURE_6009);
        }
    }

    public ScenePO createScene(String projectNum, Long cameraId, String cameraName, String phoneId, String scenepsd,
                                      String unicode, Integer cameraType, String fileId, String prefix,
                                      String imgsName, String pic, String isModel, Long userId, String userName,
                                      String algorithm, Integer sceneShootCount, String sceneName,
                                      String sceneDec, Integer sceneType, String gps,
                                      Integer type, String url, String ecsType)throws Exception{
        //先返回链接地址
        ScenePO scenePo = new ScenePO();
        Scene scene = new Scene();
        SceneExt sceneExt = new SceneExt();
        scene.setWebSite(url+projectNum);
        scene.setCameraId(cameraId);
        scene.setPhoneId(phoneId);
        scene.setNum(String.valueOf(projectNum));
        if(scenepsd == null)
        {
            scenepsd = "";
        }
        if(!scenepsd.equals(""))
        {
            scene.setSceneKey(scenepsd);
        }

        if(!org.springframework.util.StringUtils.isEmpty(ecsType)){
            sceneExt.setOss(ecsType);
        }

        String path =  ConstantFilePath.BUILD_MODEL_PATH + unicode;

        if(cameraType.longValue() >= 4){
            scene.setDataSource(ConstantFilePath.BUILD_MODEL_PATH +
                    cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator + fileId + File.separator + unicode);
        }else {
            scene.setDataSource(prefix+imgsName);
        }

        if(cameraType.longValue() == 14){

            scene.setDataSource(ConstantFilePath.BUILD_MODEL_LASER_PATH +
                    cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator +
                    fileId + File.separator + unicode);

            log.info("激光相机 dataSource ：" + scene.getDataSource());

        }

        if(pic!=null&&pic.length()>5) {
            scene.setThumb(pic);
        }else{
            scene.setThumb(ConstantUrl.DEFAULT_SCENE_PIC);
        }

        BuildSceneCallMessage buildSceneMqMessage = new BuildSceneCallMessage();
        buildSceneMqMessage.setUnicode(unicode);
        buildSceneMqMessage.setPath(path);
        buildSceneMqMessage.setPrefix(prefix);
        buildSceneMqMessage.setImgsName(imgsName);
        buildSceneMqMessage.setSceneNum(projectNum);
        buildSceneMqMessage.setIsModel(isModel);
        buildSceneMqMessage.setCameraType(String.valueOf(cameraType));
        buildSceneMqMessage.setAlgorithm(algorithm);
        buildSceneMqMessage.setFileId(fileId);
        buildSceneMqMessage.setCameraName(cameraName);

        if(StrUtil.isNotBlank(userName))
        {
            buildSceneMqMessage.setUserName(userName);
            scene.setUserId(userId);
        }
        else
        {
            buildSceneMqMessage.setUserName("noMan");
        }
//        mqProducer.syncSend(topicModelingA, buildSceneMqMessage);
        rabbitMqProducer.sendByWorkQueue(queueModelingPre, buildSceneMqMessage);

        if(sceneShootCount == null)
        {
            sceneExt.setShootCount(0);
        }
        else
        {
            sceneExt.setShootCount(sceneShootCount);
        }
        if(sceneName!=null)
        {
            scene.setSceneName(sceneName);
        }
        if(sceneDec!=null)
        {
            scene.setSceneDec("<p>"+sceneDec+"</p>");
        }

        if(sceneType!=null)
        {
            scene.setSceneType(sceneType);
        }

        if(gps!=null&&!gps.trim().equals(""))
        {
            sceneExt.setGps(gps);
        }

        sceneExt.setSceneScheme(cameraType.intValue());
        sceneExt.setAlgorithm(algorithm);
        log.info("场景记录添加到数据库："+projectNum);
        //type=0为新生成场景，其余为重新计算场景
        if(type == 0){
            sceneService.save(scene);
            sceneExt.setSceneId(scene.getId());
            sceneExtService.save(sceneExt);
        }

        JSONObject scenejson = JSONObject.parseObject(JSONObject.toJSONString(scene));
        scenejson.put("thumbImg", 0);
        scenejson.put("version", 0);
        scenejson.put("floorLogo", 0);
        if(!scenepsd.equals("")){
            scenejson.put("scenePsd", scenepsd);
            scenejson.put("public", 1);
        }else{
            scenejson.put("scenePsd", "");
            scenejson.put("public", 0);
        }
        if(cameraType < 4){
            scenejson.put("visions", 1);
        }else {
            scenejson.put("visions", 2);
        }
        scenejson.put("createTime", new DateTime(new Date()).toString("yyyy-MM-dd HH:mm"));

        File file = new File(ConstantFilePath.SCENE_PATH+"data/data"+projectNum);
        if(!file.exists()||!file.isDirectory())
        {
            file.mkdirs();
        }
        FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data/data"+projectNum+File.separator+"scene.json", scenejson.toString());
//        UploadToOssUtil.upload(ConstantFilePath.SCENE_PATH+"data/data"+projectNum+File.separator+"scene.json", "data/data"+projectNum+File.separator+"scene.json");

        //生成二维码
        MatrixToImageWriterUtil.createQRCode(url + projectNum, ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+projectNum+".png", false, null);
        MatrixToImageWriterUtil.createQRCode(url + projectNum + "&lang=en", ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+projectNum+"_en.png", false, null);
        log.info("二维码生成完成");


        BeanUtil.copyProperties(sceneExt, scenePo);
        BeanUtil.copyProperties(scene, scenePo);

        return scenePo;
    }

    public ScenePlusVO createScenePlus(String projectNum, Long cameraId, String cameraName, String phoneId, String scenepsd,
        String unicode, Integer cameraType, String fileId, String prefix,
        String imgsName, String pic, String isModel, Long userId, String userName,
        String algorithm, Integer sceneShootCount, String sceneName,
        String sceneDec, Integer sceneType, String gps,
        Integer type, String url, String ecsType)throws Exception{
        ScenePlusVO scenePlusVO = new ScenePlusVO();
        ScenePlus scenePlus = new ScenePlus();
        ScenePlusExt scenePlusExt = new ScenePlusExt();
        scenePlusExt.setWebSite(url+projectNum);
        scenePlus.setCameraId(cameraId);
        scenePlus.setPhoneId(phoneId);
        scenePlus.setNum(projectNum);
        if(scenepsd == null)
        {
            scenepsd = "";
        }
        // TODO: 2022/3/16 这里暂时不确定要不要 ---start
//        if(!scenepsd.equals(""))
//        {
//            scene.setSceneKey(scenepsd);
//        }
        // TODO: 2022/3/16 这里暂时不确定要不要 ---end

        String path =  ConstantFilePath.BUILD_MODEL_PATH + unicode;

        if(cameraType.longValue() >= 4){
            scenePlusExt.setDataSource(ConstantFilePath.BUILD_MODEL_PATH +
                cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator + fileId + File.separator + unicode);
        }else {
            scenePlusExt.setDataSource(prefix+imgsName);
        }

        if(cameraType.longValue() == 14){

            scenePlusExt.setDataSource(ConstantFilePath.BUILD_MODEL_LASER_PATH +
                cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator +
                fileId + File.separator + unicode);

            log.info("激光相机 dataSource ：" + scenePlusExt.getDataSource());

        }

        if(!org.springframework.util.StringUtils.isEmpty(ecsType)){
            scenePlusExt.setEcs(ecsType);
        }

        if(pic!=null&&pic.length()>5) {
            scenePlusExt.setThumb(pic);
        }else{
            scenePlusExt.setThumb(ConstantUrl.DEFAULT_SCENE_PIC);
        }

        BuildSceneCallMessage buildSceneMqMessage = new BuildSceneCallMessage();
        buildSceneMqMessage.setUnicode(unicode);
        buildSceneMqMessage.setPath(path);
        buildSceneMqMessage.setPrefix(prefix);
        buildSceneMqMessage.setImgsName(imgsName);
        buildSceneMqMessage.setSceneNum(projectNum);
        buildSceneMqMessage.setIsModel(isModel);
        buildSceneMqMessage.setCameraType(String.valueOf(cameraType));
        buildSceneMqMessage.setAlgorithm(algorithm);
        buildSceneMqMessage.setFileId(fileId);
        buildSceneMqMessage.setCameraName(cameraName);

        if(StrUtil.isNotBlank(userName))
        {
            buildSceneMqMessage.setUserName(userName);
            scenePlus.setUserId(userId);
        }
        else
        {
            buildSceneMqMessage.setUserName("noMan");
        }
        rabbitMqProducer.sendByWorkQueue(queueModelingPre, buildSceneMqMessage);

        if(sceneShootCount == null)
        {
            scenePlusExt.setShootCount(0);
        }
        else
        {
            scenePlusExt.setShootCount(sceneShootCount);
        }
        if(sceneName!=null)
        {
            scenePlus.setTitle(sceneName);
        }
        if(sceneDec!=null)
        {
            scenePlus.setDescription("<p>"+sceneDec+"</p>");
        }

        if(sceneType!=null)
        {
            scenePlus.setSceneType(sceneType);
        }

        if(gps!=null&&!gps.trim().equals(""))
        {
            scenePlusExt.setGps(gps);
        }

        scenePlusExt.setSceneScheme(cameraType.intValue());
        scenePlusExt.setAlgorithm(algorithm);
        log.info("场景记录添加到数据库："+projectNum);
        //type=0为新生成场景，其余为重新计算场景
        if(type == 0){
            scenePlusService.save(scenePlus);
            scenePlusExt.setPlusId(scenePlus.getId());
            scenePlusExtService.save(scenePlusExt);
        }

        BeanUtil.copyProperties(scenePlusExt, scenePlusVO);
        BeanUtil.copyProperties(scenePlus, scenePlusVO);
        JSONObject scenejson = JSONObject.parseObject(JSONObject.toJSONString(scenePlusVO));
        scenejson.put("thumbImg", 0);
        scenejson.put("version", 0);
        scenejson.put("floorLogo", 0);
        if(!scenepsd.equals("")){
            scenejson.put("scenePsd", scenepsd);
            scenejson.put("public", 1);
        }else{
            scenejson.put("scenePsd", "");
            scenejson.put("public", 0);
        }
        if(cameraType < 4){
            scenejson.put("visions", 1);
        }else {
            scenejson.put("visions", 2);
        }
        scenejson.put("createTime", new DateTime(new Date()).toString("yyyy-MM-dd HH:mm"));

        File file = new File(ConstantFilePath.SCENE_PATH+"data/data"+projectNum);
        if(!file.exists()||!file.isDirectory())
        {
            file.mkdirs();
        }
        FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data/data"+projectNum+File.separator+"scene.json", scenejson.toString());
//        UploadToOssUtil.upload(ConstantFilePath.SCENE_PATH+"data/data"+projectNum+File.separator+"scene.json", "data/data"+projectNum+File.separator+"scene.json");

        //生成二维码
        MatrixToImageWriterUtil.createQRCode(url + projectNum, ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+projectNum+".png", false, null);
        MatrixToImageWriterUtil.createQRCode(url + projectNum + "&lang=en", ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+projectNum+"_en.png", false, null);
        log.info("二维码生成完成");

        return scenePlusVO;
    }

    public SceneProPO createScenePro(String projectNum, Long cameraId, String cameraName, String phoneId, String sceneKey,
                                     String unicode, Long cameraType, String fileId, String prefix,
                                     String imgsName, String pic, String isModel, Long userId, String userName,
                                     String algorithm, Integer sceneShootCount, String sceneName,
                                     String sceneDec, Integer sceneType, String gps,Integer type,
                                     Integer resolution, String firmwareVersion, String url, String buildType, String ossType, String ecsType,
                                     Long cooperationUser)throws Exception{
        //先返回链接地址
        SceneProPO sceneProPO = new SceneProPO();
        ScenePro scenePro = new ScenePro();
        SceneProExt sceneProExt = new SceneProExt();
        scenePro.setWebSite(url+projectNum);
        scenePro.setCameraId(cameraId);
        sceneProExt.setPhoneId(phoneId);
        scenePro.setNum(projectNum);

        String path =  ConstantFilePath.BUILD_MODEL_PATH + unicode;

        sceneProExt.setSceneSource(1);
        if(cameraType.longValue() == 5 || cameraType.longValue() == 6){
            //场景来源双目相机
            sceneProExt.setSceneSource(2);
            sceneProExt.setDataSource(ConstantFilePath.BUILD_MODEL_PATH + unicode);
        }else if(cameraType.longValue() == 14){

            sceneProExt.setDataSource(ConstantFilePath.BUILD_MODEL_LASER_PATH +
                    cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator +
                    fileId + File.separator + unicode);
            path =  ConstantFilePath.BUILD_MODEL_LASER_PATH + unicode;
            log.info("激光相机 dataSource ：" + sceneProExt.getDataSource());

        }else if(cameraType.longValue() >= 3){
            sceneProExt.setDataSource(ConstantFilePath.BUILD_MODEL_PATH +
                    cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator +
                    fileId + File.separator + unicode);
        }else {
            sceneProExt.setDataSource(prefix+imgsName);
        }

        if(!org.springframework.util.StringUtils.isEmpty(ecsType)){
            sceneProExt.setEcs(ecsType);
        }

        if(resolution == null || resolution.intValue() == 0){
            scenePro.setSceneScheme(cameraType.intValue());
        }else {
            scenePro.setSceneScheme(4);
        }

        //场景来源双目相机,sceneScheme为4,加载high,low图
        if(cameraType.longValue() == 5 || cameraType.longValue() == 6){
            scenePro.setSceneScheme(4);
        }

        //转台相机用4k图
        if(cameraType.longValue() == 13 ){
            sceneProExt.setSceneSource(3);
            scenePro.setSceneScheme(10);
        }

        //激光相机
        if(cameraType.longValue() == 14 ){
            sceneProExt.setSceneSource(4);
            scenePro.setSceneScheme(10);
        }

        if(pic!=null&&pic.length()>5)
        {
            scenePro.setThumb(pic);
        }
        else
        {
            scenePro.setThumb(ConstantUrl.DEFAULT_SCENE_PIC);
        }
        scenePro.setThumb(scenePro.getThumb().concat("?t=")+System.currentTimeMillis());

        if(!ObjectUtils.isEmpty(userName)){
            scenePro.setUserId(userId);
        }

        if(sceneShootCount == null)
        {
            sceneProExt.setShootCount(0);
        }
        else
        {
            sceneProExt.setShootCount(sceneShootCount);
        }
        if(sceneName!=null)
        {
            scenePro.setSceneName(sceneName);
        }
        if(sceneDec!=null)
        {
            scenePro.setSceneDec("<p>"+ new String(sceneDec.getBytes("UTF-8"))+"</p>");
        }

        if(sceneType!=null)
        {
            scenePro.setSceneType(sceneType);
        }

        if(gps!=null&&!gps.trim().equals(""))
        {
            scenePro.setGps(gps);
        }

        sceneProExt.setAlgorithm(algorithm);
        sceneProExt.setFilesName(imgsName);
        if(!org.springframework.util.StringUtils.isEmpty(firmwareVersion)){
            sceneProExt.setFirmwareVersion(firmwareVersion);
        }
        scenePro.setBuildType(buildType);
        log.info("场景记录添加到数据库："+projectNum);
        //type=0为新生成场景，其余为重新计算场景

        // TODO: 2022/2/23  SceneProEdit 重构版本SceneProEdit 这个表可能不用，这里先暂时注释掉
        SceneProEdit sceneProEdit = new SceneProEdit();
        SceneProEditExt sceneProEditExt = new SceneProEditExt();
        if(type == 0){
            scenePro.setSceneStatus(SceneStatus.wait.code());
            sceneProService.save(scenePro);
            sceneProExt.setSceneProId(scenePro.getId());
            sceneProExtService.save(sceneProExt);

            SceneEditInfo sceneEditInfo = new SceneEditInfo();
            sceneEditInfo.setSceneProId(scenePro.getId());
            sceneEditInfoService.save(sceneEditInfo);

            sceneProEdit.setNeedKey(0);
            if(sceneKey == null) {
                sceneKey = "";
            }
            sceneProEdit.setSceneKey(sceneKey);
            if(!sceneKey.equals("")) {
                sceneProEdit.setNeedKey(1);
            }else {
                sceneProEdit.setNeedKey(0);
            }

            sceneProEdit.setProId(scenePro.getId());
            sceneProEdit.setFloorLogoSize(100);
            sceneProEdit.setCreateTime(Calendar.getInstance().getTime());
            sceneProEditService.save(sceneProEdit);

            sceneProEditExt.setProEditId(sceneProEdit.getId());
            sceneProEditExt.setProId(scenePro.getId());
            sceneProEditExt.setMapVisi(1);
            sceneProEditExt.setTourVisi(1);
            sceneProEditExt.setVrVisi(1);
            sceneProEditExt.setRulerVisi(1);
            sceneProEditExt.setCadImgVisi(1);
            sceneProEditExt.setPanoVisi(1);
            sceneProEditExt.setM2dVisi(1);
            sceneProEditExt.setM3dVisi(1);
            sceneProEditExt.setMeasureVisi(0);
            sceneProEditExt.setCreateTime(Calendar.getInstance().getTime());
            sceneProEditExtService.save(sceneProEditExt);


            //新增场景时，同时新增场景协作信息
            if(cooperationUser != null){
                SceneCooperation sceneCooperationEntity = new SceneCooperation();
                sceneCooperationEntity.setNum(projectNum);
                sceneCooperationEntity.setUserId(cooperationUser);
                sceneCooperationService.save(sceneCooperationEntity);

                List<SceneResourceCamera> resourceCameraList = sceneResourceCameraService.findListByCameraId(cameraId);

                SceneResourceCooperation sceneResourceCooperation = null;
                if(resourceCameraList != null && resourceCameraList.size() > 0){
                    for (SceneResourceCamera sceneResourceCamera : resourceCameraList) {
                        sceneResourceCooperation = new SceneResourceCooperation();
                        sceneResourceCooperation.setSceneResourceId(sceneResourceCamera.getSceneResourceId());
                        sceneResourceCooperation.setSceneCooperationId(sceneCooperationEntity.getId());
                        sceneResourceCooperationService.save(sceneResourceCooperation);
                    }
                }
            }
        }else {
            ScenePro oldScene = sceneProService.findBySceneNum(projectNum);
            scenePro.setId(oldScene.getId());
            scenePro.setSceneStatus(0);
            scenePro.setTbStatus(TbStatus.VALID.code());
            scenePro.setPayStatus(0);
            scenePro.setCreateTime(new Date());

            SceneProExt oldSceneProExt = sceneProExtService.findBySceneProId(oldScene.getId());
            sceneProExt.setSpace(oldSceneProExt.getSpace());
            sceneProExt.setEcs(oldSceneProExt.getEcs());
            sceneProExt.setViewCount(oldSceneProExt.getViewCount());
            if(sceneName!=null) {
                scenePro.setSceneName(sceneName);
            }
            if(sceneType!=null) {
                scenePro.setSceneType(sceneType);
            }
            scenePro.setUpdateTime(Calendar.getInstance().getTime());
            sceneProExt.setUpdateTime(Calendar.getInstance().getTime());
            sceneProService.updateById(scenePro);
            sceneProExtService.updateById(sceneProExt);

            // TODO: 2022/2/23 如果是重算场景 ，这里需要更新一些字段，现在还不知道更写哪些字段，先留空
            SceneEditInfo sceneEditInfo = sceneEditInfoService.getBySceneProId(oldScene.getId());
            if(sceneEditInfo == null){
                throw new BusinessException(ErrorCode.FAILURE_CODE_7008);
            }
            sceneEditInfoService.updateById(sceneEditInfo);

            SceneProEdit oldSceneProEdit = sceneProEditService.findByProId(scenePro.getId());
            SceneProEditExt oldSceneProEditeExt = sceneProEditExtService.getByProEditId(oldSceneProEdit.getId());
            sceneProEdit.setNeedKey(0);

            if(sceneKey == null) {
                sceneKey = "";
            }
            sceneProEdit.setSceneKey(sceneKey);
            if(!sceneKey.equals("")) {
                sceneProEdit.setNeedKey(1);
            }else {
                sceneProEdit.setNeedKey(0);
            }

            sceneProEdit.setId(oldSceneProEdit.getId());
            sceneProEdit.setProId(scenePro.getId());
            sceneProEdit.setFloorLogoSize(100);
            sceneProEdit.setTbStatus(TbStatus.VALID.code());
            sceneProEdit.setFloorPublishVer(oldSceneProEdit.getFloorEditVer() + 1);
            sceneProEdit.setFloorEditVer(oldSceneProEdit.getFloorEditVer() + 1);
            sceneProEdit.setVersion(oldSceneProEdit.getVersion() + 1);
            sceneProEdit.setUpdateTime(Calendar.getInstance().getTime());
            sceneProEditService.updateById(sceneProEdit);

            sceneProEditExt.setId(oldSceneProEditeExt.getId());
            sceneProEditExt.setProId(scenePro.getId());
            sceneProEditExt.setMapVisi(1);
            sceneProEditExt.setTourVisi(1);
            sceneProEditExt.setVrVisi(1);
            sceneProEditExt.setRulerVisi(1);
            sceneProEditExt.setCadImgVisi(1);
            sceneProEditExt.setPanoVisi(1);
            sceneProEditExt.setM2dVisi(1);
            sceneProEditExt.setM3dVisi(1);
            sceneProEditExt.setMeasureVisi(0);
            sceneProEditExt.setCreateTime(oldSceneProEdit.getCreateTime());
            sceneProEditExt.setImagesVersion(oldSceneProEditeExt.getImagesVersion() + 1);
            sceneProEditExt.setUpdateTime(Calendar.getInstance().getTime());
            sceneProEditExtService.updateById(sceneProEditExt);

        }

//        BuildSceneMqMessage buildSceneMqMessage =this.getBuildSceneMqMessage(
//                projectNum, cameraName, unicode, cameraType, fileId, prefix, imgsName, isModel,
//                userName, algorithm, resolution, buildType, path, scenePro.getId(), scenePro.getSceneName(),
//                scenePro.getWebSite(), scenePro.getCreateTime(), scenePro.getUserId(),
//                sceneProExt.getDataSource(), scenePro.getSceneStatus(), scenePro.getPayStatus(), scenePro.getThumb());

        BeanUtil.copyProperties(sceneProExt, sceneProPO);
        BeanUtil.copyProperties(scenePro, sceneProPO);

        JSONObject scenejson = JSONObject.parseObject(JSONObject.toJSONString(sceneProPO));
        scenejson.put("thumbImg", 0);
        scenejson.put("version", 0);
        scenejson.put("floorLogo", 0);
        if(!sceneKey.equals("")){
            scenejson.put("sceneKey", sceneKey);
            scenejson.put("public", 1);
        }else{
            scenejson.put("sceneKey", "");
            scenejson.put("public", 0);
        }
        if(cameraType.longValue() < 4 || cameraType.longValue() == 5 || cameraType.longValue() == 6){
            scenejson.put("visions", 1);
        }else {
            scenejson.put("visions", 2);
        }
        scenejson.put("createTime", new DateTime(new Date()).toString("yyyy-MM-dd HH:mm"));

        scenejson.put("floorPublishVer", sceneProEdit.getFloorPublishVer());
        scenejson.put("floorEditVer", sceneProEdit.getFloorEditVer());
        scenejson.put("entry", null);

        if(!org.springframework.util.StringUtils.isEmpty(sceneProEdit.getHotsIds())){
            scenejson.put("hots", 1);
        }

        File file = new File(ConstantFilePath.SCENE_PATH+"data/data"+projectNum);
        if(!file.exists()||!file.isDirectory())
        {
            file.mkdirs();
        }
        FileUtils.writeFile(ConstantFilePath.SCENE_PATH+"data/data"+projectNum+File.separator+"scene.json", scenejson.toString());

        //生成二维码
        MatrixToImageWriterUtil.createQRCode(url + projectNum, ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+projectNum+".png", false, null);
        MatrixToImageWriterUtil.createQRCode(url + projectNum + "&lang=en", ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+projectNum+"_en.png", false, null);
        log.info("二维码生成完成");

        //当mq排队数大于指定数量时使用弹性升缩
        return sceneProPO;
    }

    public Object[] createScenePlus2(String projectNum, Long cameraId, String cameraName, String phoneId, String sceneKey,
        String unicode, Long cameraType, String fileId, String prefix,
        String imgsName, String pic, String isModel, Long userId, String userName,
        String algorithm, Integer sceneShootCount, String sceneName,
        String sceneDec, Integer sceneType, String gps,Integer type,
        Integer resolution, String firmwareVersion, String url, String buildType, String ecsType,
        Long cooperationUser)throws Exception{

//        SceneProPO sceneProPO = new SceneProPO();
//        ScenePro scenePro = new ScenePro();
//        SceneProExt sceneProExt = new SceneProExt();
//        scenePro.setWebSite(url+projectNum);
//        scenePro.setCameraId(cameraId);
//        sceneProExt.setPhoneId(phoneId);
//        scenePro.setNum(projectNum);
        ScenePlusVO scenePlusVO = new ScenePlusVO();
        ScenePlus scenePlus = new ScenePlus();
        ScenePlusExt scenePlusExt = new ScenePlusExt();
        scenePlusExt.setWebSite(url+projectNum);
        scenePlus.setCameraId(cameraId);
        scenePlus.setPhoneId(phoneId);
        scenePlus.setNum(projectNum);

        String path =  ConstantFilePath.BUILD_MODEL_PATH + unicode;

        scenePlus.setSceneSource(1);
        if(cameraType.longValue() == 5 || cameraType.longValue() == 6){
            //场景来源双目相机
            scenePlus.setSceneSource(2);
            scenePlusExt.setDataSource(ConstantFilePath.BUILD_MODEL_PATH + unicode);
        }else if(cameraType.longValue() == 14){

            scenePlusExt.setDataSource(ConstantFilePath.BUILD_MODEL_LASER_PATH +
                cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator +
                fileId + File.separator + unicode);
            path =  ConstantFilePath.BUILD_MODEL_LASER_PATH + unicode;
            log.info("激光相机 dataSource ：" + scenePlusExt.getDataSource());

        }else if(cameraType.longValue() >= 3){
            scenePlusExt.setDataSource(ConstantFilePath.BUILD_MODEL_PATH +
                cameraName.replace("4DKKPRO_", "").replace("-fdage", "").toLowerCase() + File.separator +
                fileId + File.separator + unicode);
        }else {
            scenePlusExt.setDataSource(prefix+imgsName);
        }

        if(!org.springframework.util.StringUtils.isEmpty(ecsType)){
            scenePlusExt.setEcs(ecsType);
        }

        if(resolution == null || resolution.intValue() == 0){
            scenePlusExt.setSceneScheme(cameraType.intValue());
        }else {
            scenePlusExt.setSceneScheme(4);
        }

        //场景来源双目相机,sceneScheme为4,加载high,low图
        if(cameraType.longValue() == 5 || cameraType.longValue() == 6){
            scenePlusExt.setSceneScheme(4);
        }

        //转台相机用4k图
        if(cameraType.longValue() == 13 ){
            scenePlus.setSceneSource(3);
            scenePlusExt.setSceneScheme(10);
        }

        //激光相机
        if(cameraType.longValue() == 14 ){
            scenePlus.setSceneSource(4);
            scenePlusExt.setSceneScheme(10);
        }

        if(pic!=null&&pic.length()>5)
        {
            scenePlusExt.setThumb(pic);
        }
        else
        {
            scenePlusExt.setThumb(ConstantUrl.DEFAULT_SCENE_PIC);
        }
        scenePlusExt.setThumb(scenePlusExt.getThumb().concat("?t=")+System.currentTimeMillis());

        if(!ObjectUtils.isEmpty(userName)){
            scenePlus.setUserId(userId);
        }

        if(sceneShootCount == null)
        {
            scenePlusExt.setShootCount(0);
        }
        else
        {
            scenePlusExt.setShootCount(sceneShootCount);
        }
        if(sceneName!=null)
        {
            scenePlus.setTitle(sceneName);
        }
        if(sceneDec!=null)
        {
            scenePlus.setDescription("<p>"+ new String(sceneDec.getBytes("UTF-8"))+"</p>");
        }

        if(sceneType!=null)
        {
            scenePlus.setSceneType(sceneType);
        }

        if(gps!=null&&!gps.trim().equals(""))
        {
            scenePlusExt.setGps(gps);
        }

        scenePlusExt.setAlgorithm(algorithm);
        if(!org.springframework.util.StringUtils.isEmpty(firmwareVersion)){
            scenePlusExt.setFirmwareVersion(firmwareVersion);
        }
        scenePlusExt.setBuildType(buildType);
        log.info("场景记录添加到数据库："+projectNum);
        //type=0为新生成场景，其余为重新计算场景

        SceneEditInfo sceneEditInfo = new SceneEditInfo();
        SceneEditInfoExt sceneEditInfoExt = new SceneEditInfoExt();
        SceneEditControls sceneEditControls = new SceneEditControls();
        if(type == 0){
            scenePlus.setSceneStatus(SceneStatus.wait.code());
            scenePlusService.save(scenePlus);
            scenePlusExt.setPlusId(scenePlus.getId());
            scenePlusExtService.save(scenePlusExt);

            sceneEditInfo.setScenePlusId(scenePlus.getId());

            if(StrUtil.isNotBlank(sceneKey)) {
                sceneEditInfo.setScenePassword(sceneKey);
                sceneEditControls.setShowLock((int) CommonStatus.YES.code());
            }

            sceneEditInfoService.save(sceneEditInfo);
            sceneEditControls.setEditInfoId(sceneEditInfo.getId());
            sceneEditControlsService.save(sceneEditControls);

            //新增场景时，同时新增场景协作信息
            if(cooperationUser != null){
                SceneCooperation sceneCooperationEntity = new SceneCooperation();
                sceneCooperationEntity.setNum(projectNum);
                sceneCooperationEntity.setUserId(cooperationUser);
                sceneCooperationService.save(sceneCooperationEntity);

                List<SceneResourceCamera> resourceCameraList = sceneResourceCameraService.findListByCameraId(cameraId);

                SceneResourceCooperation sceneResourceCooperation = null;
                if(resourceCameraList != null && resourceCameraList.size() > 0){
                    for (SceneResourceCamera sceneResourceCamera : resourceCameraList) {
                        sceneResourceCooperation = new SceneResourceCooperation();
                        sceneResourceCooperation.setSceneResourceId(sceneResourceCamera.getSceneResourceId());
                        sceneResourceCooperation.setSceneCooperationId(sceneCooperationEntity.getId());
                        sceneResourceCooperationService.save(sceneResourceCooperation);
                    }
                }
            }
        }else {
            ScenePlus oldScene = scenePlusService.getScenePlusByNum(projectNum);
            scenePlus.setId(oldScene.getId());
            scenePlus.setSceneStatus(0);
            scenePlus.setTbStatus(TbStatus.VALID.code());
            scenePlus.setPayStatus(0);
            scenePlus.setCreateTime(Calendar.getInstance().getTime());

            ScenePlusExt oldSceneExt = scenePlusExtService.getScenePlusExtByPlusId(oldScene.getId());
            scenePlusExt.setSpace(oldSceneExt.getSpace());
            scenePlusExt.setEcs(oldSceneExt.getEcs());
            scenePlusExt.setViewCount(oldSceneExt.getViewCount());
            if(sceneName!=null) {
                scenePlus.setTitle(sceneName);
            }
            if(sceneType!=null) {
                scenePlus.setSceneType(sceneType);
            }
            scenePlusService.updateById(scenePlus);
            scenePlusExtService.updateById(scenePlusExt);

            SceneEditInfo oldSceneEditInfo = sceneEditInfoService.getByScenePlusId(oldScene.getId());
            SceneEditInfoExt oldSceneEditeIinfoExt = sceneEditInfoExtService.getByEditInfoId(oldSceneEditInfo.getId());
            if(StrUtil.isNotBlank(sceneKey)) {
                sceneEditInfo.setScenePassword(sceneKey);
                sceneEditControls.setShowLock((int) CommonStatus.YES.code());
            }else{
                sceneEditInfo.setScenePassword("");
                sceneEditControls.setShowLock((int)CommonStatus.NO.code());
            }

            sceneEditInfo.setId(oldSceneEditInfo.getId());
            sceneEditInfo.setScenePlusId(scenePlus.getId());
            sceneEditInfo.setFloorLogoSize(100);
            sceneEditInfo.setTbStatus(TbStatus.VALID.code());
            sceneEditInfo.setFloorPublishVer(oldSceneEditInfo.getFloorEditVer() + 1);
            sceneEditInfo.setFloorEditVer(oldSceneEditInfo.getFloorEditVer() + 1);
            sceneEditInfo.setVersion(oldSceneEditInfo.getVersion() + 1);
            sceneEditInfoService.updateById(sceneEditInfo);

            sceneEditInfoExt.setId(oldSceneEditeIinfoExt.getId());
            sceneEditInfoExt.setEditInfoId(sceneEditInfo.getId());
            sceneEditInfoExt.setScenePlusId(scenePlus.getId());
            sceneEditInfoExtService.updateById(sceneEditInfoExt);

        }

        BuildSceneCallMessage buildSceneMqMessage =this.getBuildSceneMqMessage(
            projectNum, cameraName, unicode, cameraType, fileId, prefix, imgsName, isModel,
            userName, algorithm, resolution, buildType, path, scenePlus.getId(), scenePlus.getTitle(),
            scenePlusExt.getWebSite(), scenePlus.getCreateTime(), scenePlus.getUserId(),
            scenePlusExt.getDataSource(), scenePlus.getSceneStatus(), scenePlus.getPayStatus(), scenePlusExt.getThumb());

        BeanUtil.copyProperties(scenePlusExt, scenePlusVO);
        BeanUtil.copyProperties(scenePlus, scenePlusVO);


        //当mq排队数大于指定数量时使用弹性升缩
        return new Object[]{scenePlusVO, buildSceneMqMessage};
    }

    public BuildSceneCallMessage getBuildSceneMqMessage(String projectNum, String cameraName, String unicode,
                                                             Long cameraType, String fileId,String prefix, String imgsName,
                                                             String isModel, String userName,String algorithm, Integer resolution,
                                                             String buildType, String path, Long sceneProId, String sceneName, String webSite,
                                                             Date sceneProCreateTime, Long userId, String dataSource,
                                                             Integer sceneStatus, Integer PayStatus, String thumb) {
        BuildSceneCallMessage mqMsg = new BuildSceneCallMessage();
        mqMsg.setSceneProId(sceneProId);
        mqMsg.setSceneNum(projectNum);
        mqMsg.setCameraName(cameraName);
        mqMsg.setUnicode(unicode);
        mqMsg.setCameraType(String.valueOf(cameraType));
        mqMsg.setFileId(fileId);
        mqMsg.setPrefix(prefix);
        mqMsg.setImgsName(imgsName);
        mqMsg.setIsModel(isModel);
        mqMsg.setUserName(userName);
        mqMsg.setAlgorithm(algorithm);
        mqMsg.setResolution(String.valueOf(resolution));
        mqMsg.setBuildType(buildType);
        mqMsg.setPath(path);
        mqMsg.setSceneName(sceneName);
        mqMsg.setWebSite(webSite);
        mqMsg.setSceneProCreateTime(sceneProCreateTime);
        mqMsg.setUserId(userId);
        mqMsg.setDataSource(dataSource);
        mqMsg.setSceneStatus(sceneStatus);
        mqMsg.setPayStatus(PayStatus);
        mqMsg.setCreateTime(DateUtil.format(Calendar.getInstance().getTime(), DateExtUtil.dateStyle));
        mqMsg.setThumb(thumb);
        return mqMsg;
    }



    public String saveFile(MultipartFile file, String filePath, String fileId) throws IOException {
        //扩展名格式
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String name;
        /*
          指定上传目录
         */
        if (filePath != null && !"".equals(filePath.trim())) {
            name = designatedUp(filePath, fileId, file);
            return name;
        }
        /*
          默认上传目录
         */
        //图片类型文件
        if (this.inArray(routeConfig.getImageType(), extName)) {
            filePath = routeConfig.getImageFolder();
        }
        //视频类型文件
        else if (this.inArray(routeConfig.getVideoType(), extName)) {
            filePath = routeConfig.getVideoFolder();
        }
        //文档类型文件
        else if (this.inArray(routeConfig.getDocumentType(), extName)) {
            filePath = routeConfig.getDocumentFolder();
        }
        //音频类型文件
        else if (this.inArray(routeConfig.getMusicType(), extName)) {
            filePath = routeConfig.getMusicFolder();
        } else {
            return "This upload type is not supported temporarily";
        }
        name = myfileUp(filePath, file);
        return name;
    }

    /**
     * 删除文件
     *
     * @param filePath 包含文件路径的文件名
     * @return
     */
    public String dropFile(String filePath) {
        try {
            FileUtil.delFile(routeConfig.getHardDisk() + File.separator + filePath);
            return "successful operation";
        } catch (Exception e) {
            return "drop file error";
        }
    }

    /**
     * 判断数组中是否包含某个元素
     *
     * @param array   类型的数组
     * @param element 被检查的类型
     * @return
     */
    private boolean inArray(String[] array, String element) {
        boolean flag = false;
        for (String type : array) {
            if (element.equals(type)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 默认上传文件到文件夹
     *
     * @param folder 默认文件夹
     * @param file   上传的文件
     * @return
     */
    private String myfileUp(String folder, MultipartFile file) throws IOException {
        LocalDate today = LocalDate.now();
        String saveName = File.separator + today.getYear() + "." + today.getMonthValue() + File.separator;
        String fileCode = UUID.randomUUID().toString().trim().replaceAll("-", "");
        String returnName = FileUpload.fileUp(file, routeConfig.getHardDisk() + File.separator + folder + saveName, fileCode);
        saveName = folder + File.separator + saveName + File.separator + returnName;
        log.warn("This file has been uploaded: " + saveName);
        return saveName;
    }

    /**
     * 指定目录上传文件
     *
     * @param folder 指定文件夹
     * @param file   上传文件
     * @return
     */
    private String designatedUp(String folder, String fileId, MultipartFile file) throws IOException {
        StringBuffer sb = new StringBuffer(routeConfig.getHardDisk()).append(File.separator).append(folder);
        String returnName = FileUpload.fileUp(file, sb.toString(), fileId);
        String filePathName = sb.toString() + File.separator + File.separator + returnName;
        log.warn("This file has been uploaded: " + filePathName);
        return filePathName;
    }

    public ResultData rebuildScene(String num) throws Exception {
        if (StringUtils.isEmpty(num)) {
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }

        // TODO: 2022/3/16 旧主表逻辑, 待删除 -------------------------------start
        ScenePro scenePro = sceneProService.findBySceneNum(num);
//        SceneProExt sceneProExt = null;
        ScenePO scenePO = null;
//        String path = "";
//        if(scenePro == null){
//            scenePO = sceneService.findBySceneNum(sceneCode);
//            if(scenePO == null){
//                throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
//            }else {
//                path = ConstantFilePath.BUILD_MODEL_PATH + scenePO.getDataSource().split("/")[scenePO.getDataSource().split("/").length - 2];
//            }
//        }else {
//            sceneProExt = sceneProExtService.findBySceneProId(scenePro.getId());
//            path = sceneProExt.getDataSource();
//        }
//        Integer sceneSource = sceneProExt.getSceneSource();
//        String dataSource = sceneProExt.getDataSource();
//        Long sceneUserId = scenePro.getUserId();
//        String buildType = scenePro.getBuildType();
//        Integer sceneStatus = scenePro.getSceneStatus();
//        String webSite = scenePro.getWebSite();
//        String thumb = scenePro.getThumb();
//        Integer payStatus = scenePro.getPayStatus();
//        Integer sceneScheme = scenePro.getSceneScheme();
//        Long sceneId = scenePro.getId();
//        String sceneName = scenePro.getSceneName();
//        Date createTime = scenePro.getCreateTime();

        // TODO: 2022/3/16 旧主表逻辑, 待删除 -------------------------------end

        ScenePlusVO scenePlusVO = null;
        ScenePlus scenePlus = scenePlusService.getScenePlusByNum(num);
        if(Objects.isNull(scenePlus)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
        }
        ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
        String path = scenePlusExt.getDataSource();
        Integer sceneSource = scenePlus.getSceneSource();
        String dataSource = scenePlusExt.getDataSource();
        Long sceneUserId = scenePlus.getUserId();
        String buildType = scenePlusExt.getBuildType();
        Integer sceneStatus = scenePlus.getSceneStatus();
        String webSite = scenePlusExt.getWebSite();
        String thumb = scenePlusExt.getThumb();
        Integer payStatus = scenePlus.getPayStatus();
        Integer sceneScheme = scenePlusExt.getSceneScheme();
        Long sceneId = scenePlus.getId();
        String sceneName = scenePlus.getTitle();
        Date createTime = scenePlus.getCreateTime();

        //重新计算时需要删除文件夹，否知使用缓存
        FileUtils.delAllFile(path + File.separator + "results");

        String fileId = path.split("/")[path.split("/").length - 2];
        log.info("fileId:" + fileId);
        //获取解压后的资源的data.fdage中的数据
        File folderPath = new File(path);

        if ("aws".equals(type)) {
            CreateObjUtil.ossUtilCp(ConstantFilePath.OSS_PREFIX + path.replace(ConstantFilePath.BUILD_MODEL_PATH, ""),
                    path + "/capture/");
        } else {
            if(sceneSource == 4){
                CreateObjUtil.ossUtilCp(ConstantFilePath.OSS_PREFIX + path.replace(ConstantFilePath.BUILD_MODEL_LASER_PATH, "") + "/data.fdage", path + "/capture/");
            }else{
                CreateObjUtil.ossUtilCp(ConstantFilePath.OSS_PREFIX + path.replace(ConstantFilePath.BUILD_MODEL_PATH, "") + "/data.fdage", path + "/capture/");
            }
        }
        String data = FileUtils.readFile(folderPath.getAbsolutePath() + File.separator + "capture" + File.separator + "data.fdage");
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
        if(ObjectUtils.isEmpty(jsonObject)){
            log.error("data.fdage文件不存在");
            return ResultData.error(CameraConstant.FAILURE_6009.code(), CameraConstant.FAILURE_6009.message());
        }

        //有points字段的是八目
        if (!jsonObject.containsKey("points")) {
            String cameraName = jsonObject.getString("camid");
            ResultData<Camera> cameraResult = platformGoodsClient.getCameraByChildName(cameraName);
            Camera camera = cameraResult.getData();
            if (camera == null) {
                log.error("该相机不存在：" + cameraName);
                throw new BusinessException(CameraConstant.FAILURE_6003);
            }

            ResultData<CameraDetail> detailResult = platformGoodsClient.getCameraDetailByCameraId(camera.getId());
            CameraDetail detail = detailResult.getData();
            if (detail == null) {
                log.error("该相机详情不存在：" + cameraName);
                throw new BusinessException(CameraConstant.FAILURE_6003);
            }

            Long userId = null;
            String userName = null;

            if (detail.getUserId() != null) {
                ResultData<SSOUser> ssoUserResult = platformUserClient.getSSOUserByUserId(detail.getUserId());
                SSOUser user = ssoUserResult.getData();
                if (user == null) {
                    log.error("用户id不存在：" + detail.getUserId());
                } else {
                    userId = user.getId();
                    userName = user.getUserName();
                }
            }

            String unicode = jsonObject.getString("creator") + "_" + jsonObject.getString("uuidtime");
            // TODO: 2022/3/16 旧主表逻辑, 待删除 -------------------------------start
//            scenePO = this.createScene(num, camera.getId(),
//                cameraName, jsonObject.getString("creator"),
//                jsonObject.getString("pwd"), unicode, detail.getCameraType(),
//                fileId, "http://creator.4dkankan.com/" + unicode + File.separator, "zip.Zip",
//                jsonObject.getString("scenePic"), "0", userId, userName,
//                jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
//                jsonObject.getJSONArray("imgs").size(), jsonObject.getString("name"), jsonObject.getString("info"),
//                jsonObject.getInteger("scenetype"), jsonObject.getString("gps"),
//                1, mainUrl + sceneUrl, ecsType);
            // TODO: 2022/3/16 旧主表逻辑, 待删除 -------------------------------end

            scenePlusVO = this.createScenePlus(num, camera.getId(),
                    cameraName, jsonObject.getString("creator"),
                    jsonObject.getString("pwd"), unicode, detail.getCameraType(),
                    fileId, "http://creator.4dkankan.com/" + unicode + File.separator, "zip.Zip",
                    jsonObject.getString("scenePic"), "0", userId, userName,
                    jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                    jsonObject.getJSONArray("imgs").size(), jsonObject.getString("name"), jsonObject.getString("info"),
                    jsonObject.getInteger("scenetype"), jsonObject.getString("gps"),
                    1, mainUrl + sceneUrl, ecsType);
        } else {
            String cameraName = jsonObject.getJSONObject("cam").getString("uuid");
            String userName = null;
            if (!ObjectUtils.isEmpty(sceneUserId)) {
                ResultData<SSOUser> ssoUserResult = platformUserClient.getSSOUserByUserId(sceneUserId);
                SSOUser user = ssoUserResult.getData();
                userName = user.getUserName();
            }
            //重算的场景，先移除该场景对应的容量
            scenePlusService.resetSpace(num);
            // TODO: 2022/3/19 plus版本稳定后需要删除---------------start
            sceneProService.rebuildReduceSpaceBySceneNum(num);
            // TODO: 2022/3/19 plus版本稳定后需要删除---------------end

            JSONObject statusJson = new JSONObject();
            //临时将-2改成1，app还没完全更新
            statusJson.put("status", sceneStatus == -2 ? 1 : sceneStatus);
            statusJson.put("webSite", webSite);
            statusJson.put("sceneNum", num);
            statusJson.put("thumb", thumb);
            statusJson.put("payStatus", payStatus);
            FileUtils.writeFile(ConstantFilePath.SCENE_PATH + "data/data" + num + File.separator + "status.json", statusJson.toString());
            uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH + "data/data" + num + File.separator + "status.json",
                    "data/data" + num + File.separator + "status.json");
            String unicode = jsonObject.getString("creator") + "_" + jsonObject.getString("uuidtime");

            Long cameraType = (long)sceneScheme == 3 ? 12 : (long)sceneScheme;
            //判断是否转台相机
            if(sceneSource == 3){
                cameraType = 13L;
            }

            if(sceneSource == 4){
                cameraType = 14L;
            }

            if(sceneSource == 4){
                fdkkLaserService.updateSceneStatus(num,0);
                BuildSceneCallMessage buildSceneMqMessage =this.getBuildSceneMqMessage(
                    num, cameraName, unicode, cameraType, fileId,
                    dataSource.replace(ConstantFilePath.BUILD_MODEL_PATH, "")
                        .replace(ConstantFilePath.BUILD_MODEL_LASER_PATH,"")+ File.separator,
                    "zip.Zip", "0",
                    userName, jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                    jsonObject.getInteger("resolution"), buildType,
                    ConstantFilePath.BUILD_MODEL_LASER_PATH + unicode, sceneId, sceneName,
                    webSite, createTime, sceneUserId, dataSource, sceneStatus, payStatus, thumb);
                rabbitMqProducer.sendByWorkQueue(queueModelingPre, buildSceneMqMessage);
            }else{
                BuildSceneCallMessage buildSceneMqMessage =this.getBuildSceneMqMessage(
                    num, cameraName, unicode, cameraType, fileId,
                    dataSource.replace(ConstantFilePath.BUILD_MODEL_PATH, "")
                        .replace(ConstantFilePath.BUILD_MODEL_LASER_PATH,"")+ File.separator,
                    "zip.Zip", "0",
                    userName, jsonObject.getString("location") != null && "1".equals(jsonObject.getString("location")) ? "sfm" : "slam",
                    jsonObject.getInteger("resolution"), buildType,
                    ConstantFilePath.BUILD_MODEL_PATH + unicode, sceneId, sceneName,
                    webSite, createTime, sceneUserId, dataSource, sceneStatus, payStatus, thumb);

                rabbitMqProducer.sendByWorkQueue(queueModelingPre, buildSceneMqMessage);
            }

            // TODO: plus版本稳定后删除 -------------------------------start
            sceneProService.updateStatus(num,0);
            // TODO: plus版本稳定后删除 -------------------------------end

            scenePlusService.update(new LambdaUpdateWrapper<ScenePlus>()
                .set(ScenePlus::getSceneStatus, SceneStatus.wait.code())
                .eq(ScenePlus::getNum, num));

            // TODO: 2022/3/16 旧主表逻辑, 待删除 -------------------------------start
            // 更新imageVersion
//            sceneProEditService.updateImageVersionByProId(scenePro.getId());
            // TODO: 2022/3/16 旧主表逻辑, 待删除 -------------------------------end
        }
        log.info("生成新的场景重新计算");
        return ResultData.ok();
    }

    public ResultData rebuildVideoScene(RebuildVedioSceneParamVO param) throws Exception {

        if(StringUtils.isEmpty(param.getNum()) || StringUtils.isEmpty(param.getPanoId())){
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }

        String num = param.getNum();

        ScenePro scenePro = sceneProService.findBySceneNum(num);
        SceneProExt sceneProExt = null;
        ScenePO scene = null;
        String path = "";
        if(scenePro == null){
            scene = sceneService.findBySceneNum(num);
            if(scene == null){
                throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
            }else {
                path = ConstantFilePath.BUILD_MODEL_PATH + scene.getDataSource().split("/")[scene.getDataSource().split("/").length - 2];
            }
        }else {
            sceneProExt = sceneProExtService.findBySceneProId(scenePro.getId());
            path = sceneProExt.getDataSource();
        }

        //先从备份文件下拉取
        CreateObjUtil.ossUtilCp("video/video" +scenePro.getNum()  + File.separator + "back" + File.separator,
                sceneProExt.getDataSource() + "_rv" + File.separator + "videoback_temp");

        String backpathtemp = sceneProExt.getDataSource() + "_rv" + File.separator + "videoback_temp";
        File fileback = new File(backpathtemp);
        File[] filebackList = fileback.listFiles();

        if(filebackList.length<=0){
            String backpath = sceneProExt.getDataSource() + "_rv" + File.separator + "videoback";
            log.info("------------------" +  backpath);

            File file = new File(backpath);

            //验证video 文件夹下是否有备份
            CreateObjUtil.ossUtilCp("video/video" +scenePro.getNum()  + File.separator,
                    sceneProExt.getDataSource() + "_rv" + File.separator + "videoback");

            String name = "";
            Map<String,String> map = new HashMap<>();
            file = new File(backpath);
            File[] fileList = file.listFiles();
            if(fileList.length>0){
                for(File f:fileList){
                    name = f.getName();
                    log.info("file name :" + name);
                    map.put(sceneProExt.getDataSource() + "_rv" + File.separator + "videoback" + File.separator + name,
                            "video/video" +scenePro.getNum()  + File.separator + "back" + File.separator + name);

                }
            }
            //上传
            log.info("上传内容 ===== + " + map);
            uploadToOssUtil.uploadMulFiles(map);
            FileUtils.deleteDirectory(backpathtemp);
        }


        //更新旧记录
        videoSceneProgressService.updateProgressRec(param);

        //往文件中写入值
        JSONObject reObject = new JSONObject();
        JSONObject Object = new JSONObject();
        Object.put("name",param.getPanoId());
        Object.put("x",param.getX());
        Object.put("y",param.getY());
        Object.put("width",param.getW());
        Object.put("height",param.getH());
        JSONArray arrayRe = new JSONArray();
        arrayRe.add(Object);
        reObject.put("required_videos",arrayRe);

        JSONObject hdrObject = new JSONObject();
        if(StringUtils.isNotEmpty(scenePro.getVideos())){
            JSONObject object = JSONObject.parseObject(scenePro.getVideos());
            if(object.containsKey("data")){
                JSONArray array = new JSONArray();
                array = (JSONArray) object.get("data");
                arrayRe = new JSONArray();
                if(array.size()>0){
                    for(int i = 0; i < array.size(); i++) {
                        JSONObject obj = (JSONObject) array.get(i);
                        Object = new JSONObject();
                        Object.put("name",(String) obj.get("id"));
                        Object.put("value",(String) obj.get("value"));
                        Object.put("fov",(String) obj.get("blend_fov"));
                        arrayRe.add(Object);
                    }
                    hdrObject.put("hdr_param",arrayRe);
                }
            }
        }else{
            hdrObject.put("hdr_param","{}");
        }

        //重新计算时需要删除文件夹，否知使用缓存
        log.info("开始清除result");
        FileUtils.delAllFile(path + File.separator + "results");
        log.info("清除result结束");

        String fileId = path.split("/")[path.split("/").length - 2];
        log.info("fileId:" + fileId);

        String parametr = "";
        parametr += scenePro.getNum() + ":;" +
                param.getPanoId();



        long start = System.currentTimeMillis();

        VideoSceneProgress videoSceneProgress= new VideoSceneProgress();
        videoSceneProgress.setNum(scenePro.getNum());
        videoSceneProgress.setVideoName(param.getPanoId());
        videoSceneProgress.setDataSource(sceneProExt.getDataSource());
        videoSceneProgress.setRebuildResult(2);
        videoSceneProgress.setDataSource(sceneProExt.getDataSource());
        videoSceneProgress.setRebuildQueueStartTime(new Date());
        videoSceneProgress.setHdrParam(hdrObject.toJSONString());
        videoSceneProgress.setRebuildParam(reObject.toJSONString());
        videoSceneProgressService.save(videoSceneProgress);

        rabbitMqProducer.sendByWorkQueue(queueVideoA, parametr);

        return ResultData.ok();
    }

    public ResultData rebuildPicScene(@RequestBody RebuildVedioSceneParamVO param) throws Exception {

        if(StringUtils.isEmpty(param.getNum())){
            throw new BusinessException(ErrorCode.PARAM_REQUIRED);
        }

        String num = param.getNum();

        ScenePro scenePro = sceneProService.findBySceneNum(num);
        String path = "";
        if(scenePro == null){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
        }
        SceneProExt sceneProExt = sceneProExtService.findBySceneProId(scenePro.getId());

        path = sceneProExt.getDataSource();

        PicSceneProgress picSceneProgressFromDb = picSceneProgressService.findrebuildVideoProgressDetail(num,null);
        if(!ObjectUtils.isEmpty(picSceneProgressFromDb) && (picSceneProgressFromDb.getRebuildResult() == 2 || picSceneProgressFromDb.getRebuildResult() == 3)){
            return ResultData.error(ErrorCode.FAILURE_CODE_5035);
        }

        //更新旧记录
        picSceneProgressService.updateProgressRec(param);

        //重新计算时需要删除文件夹，否知使用缓存
        log.info("开始清除result");
        FileUtils.delAllFile(path + File.separator + "results");
        log.info("清除result结束");

        String fileId = path.split("/")[path.split("/").length - 2];
        log.info("fileId:" + fileId);

        PicSceneProgress picSceneProgress = new PicSceneProgress();
        picSceneProgress.setNum(scenePro.getNum());
        picSceneProgress.setVideoName(param.getPanoId());
        picSceneProgress.setDataSource(sceneProExt.getDataSource());
        picSceneProgress.setRebuildResult(2);
        picSceneProgress.setDataSource(sceneProExt.getDataSource());
        picSceneProgress.setRebuildQueueStartTime(new Date());
        picSceneProgress.setRebuildParam(JSONObject.toJSONString(param));
        picSceneProgressService.save(picSceneProgress);

        String parametr = picSceneProgress.getId()+"";
        rabbitMqProducer.sendByWorkQueue(queuePicA, parametr);

        return ResultData.ok();
    }

}
