package com.fdkankan.scene.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
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.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.*;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.model.constants.ConstantFilePath;
import com.fdkankan.model.constants.UploadFilePath;
import com.fdkankan.model.utils.FloorPlanUserUtil;
import com.fdkankan.scene.bean.SceneBean;
import com.fdkankan.scene.entity.SceneEditInfoExt;
import com.fdkankan.scene.entity.ScenePro;
import com.fdkankan.scene.service.ISceneEditInfoExtService;
import com.fdkankan.scene.service.ISceneProService;
import com.fdkankan.web.response.ResultData;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.constant.RedisLockKey;
import com.fdkankan.redis.util.RedisLockUtil;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.scene.bean.LaserSceneBean;
import com.fdkankan.scene.bean.SceneJsonBean;
import com.fdkankan.scene.config.FdkkLaserConfig;
import com.fdkankan.scene.entity.*;
import com.fdkankan.scene.mapper.IScenePlusMapper;
import com.fdkankan.scene.oss.OssUtil;
import com.fdkankan.scene.service.*;
import com.fdkankan.scene.vo.SceneCheckKeyParamVO;
import com.fdkankan.scene.vo.SceneDataDownloadVO;
import com.fdkankan.scene.vo.SceneEditControlsVO;
import com.fdkankan.web.response.ResultData;
import java.io.File;
import java.nio.file.FileSystemException;
import java.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
/**
*
* 场景主表 服务实现类
*
*
* @author
* @since 2022-03-16
*/
@Slf4j
@Service
public class ScenePlusServiceImpl extends ServiceImpl implements IScenePlusService {
@Value("${main.url}")
private String mainUrl;
@Value("${scene.pro.new.url}")
private String sceneProNewUrl;
@Autowired
private IScenePlusExtService scenePlusExtService;
@Autowired
private IScenePlusService scenePlusService;
@Autowired
private ISceneEditInfoService sceneEditInfoService;
@Autowired
private ISceneDataDownloadService sceneDataDownloadService;
@Autowired
private RedisUtil redisUtil;
@Autowired
private RedisLockUtil redisLockUtil;
@Autowired
private ISceneEditInfoExtService sceneEditInfoExtService;
@Autowired
private ISceneEditControlsService sceneEditControlsService;
@Autowired
private OssUtil ossUtil;
@Autowired
FdkkLaserConfig fdkkLaserConfig;
@Autowired
private ISceneProService sceneProService;
@Autowired
private ISceneDelLogService sceneDelLogService;
@Override
public ScenePlus getScenePlusByNum(String num) {
return this.getOne(new LambdaQueryWrapper().eq(ScenePlus::getNum, num));
}
@Override
public ResultData checkKey(SceneCheckKeyParamVO param) throws Exception {
ScenePlus scenePlus = scenePlusService.getOne(new LambdaQueryWrapper()
.eq(ScenePlus::getNum, param.getNum())
.eq(ScenePlus::getPayStatus, PayStatus.PAY.code()));
if (Objects.isNull(scenePlus)) {
throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
}
SceneEditInfo sceneEditInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
if (Objects.isNull(sceneEditInfo)) {
throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
}
if(!param.getPassword().equals(sceneEditInfo.getScenePassword())){
throw new BusinessException(ErrorCode.FAILURE_CODE_5021);
}
return ResultData.ok();
}
@Override
public ResultData updateScenePlusUserIdByCameraId(List cameraIdList, Long userId) {
LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper()
.set(ScenePlus::getUserId, userId).in(ScenePlus::getCameraId, cameraIdList);
this.update(updateWrapper);
return ResultData.ok();
}
@Override
public ResultData moveScene(List numList, Long cameraId, Long userId) {
LambdaUpdateWrapper updateWrapper =
new LambdaUpdateWrapper()
.set(ScenePlus::getUserId, userId)
.set(ScenePlus::getCameraId, cameraId)
.in(ScenePlus::getNum, numList);
this.update(updateWrapper);
return ResultData.ok();
}
@Override
public ResultData downLoadZSData(String num) throws Exception {
if(StrUtil.isEmpty(num)){
throw new BusinessException(ErrorCode.FAILURE_CODE_3001);
}
String version = "v4";
ScenePlus scenePlus = this.getScenePlusByNum(num);
ScenePro scenePro = null;
if(Objects.isNull(scenePlus)){
scenePro = sceneProService.getByNum(num);
version = "v3";
if(Objects.isNull(scenePro)){
throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
}
}
SceneDataDownload sceneDataDownload = sceneDataDownloadService.findBySceneNum(num);
if(sceneDataDownload == null){
throw new BusinessException(ErrorCode.FAILURE_CODE_5025);
}
SceneDataDownloadVO sceneDataDownloadVO = BeanUtil.copyProperties(sceneDataDownload, SceneDataDownloadVO.class);
sceneDataDownloadVO.setVersion(version);
return ResultData.ok(sceneDataDownloadVO);
}
@Override
public ScenePlus checkSceneAvail(String num) {
ScenePlus scenePlus = this.getScenePlusByNum(num);
if(Objects.isNull(scenePlus)){
throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
}
if(!SceneStatus.SUCCESS.code().equals(scenePlus.getSceneStatus())
&& !SceneStatus.NO_DISPLAY.code().equals(scenePlus.getSceneStatus())){
throw new BusinessException(ErrorCode.FAILURE_CODE_5033);
}
if(!PayStatus.PAY.code().equals(scenePlus.getPayStatus())){
throw new BusinessException(ErrorCode.FAILURE_CODE_5034);
}
return scenePlus;
}
@Override
public ResultData updateViewCount(String sceneNum) {
String key = RedisKey.SCENE_VISIT_CNT;
if(!redisUtil.hHasKey(key, sceneNum)){
String lockKey = String.format(RedisLockKey.LOCK_SCENE_VISIT_CNT, sceneNum);
String lockVal = cn.hutool.core.lang.UUID.randomUUID().toString();
boolean lock = redisLockUtil.lock(lockKey, lockVal, RedisKey.EXPIRE_TIME_10_MINUTE);
if(!lock){
return ResultData.ok();
}
try {
String cnt = redisUtil.hget(key, sceneNum);
if(StrUtil.isEmpty(cnt)){
//标记是否找到了场景,如果找到就不往下找
Integer viewCount = null;
ScenePlus scenePlus = scenePlusService.getScenePlusByNum(sceneNum);
ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
viewCount = scenePlusExt.getViewCount();
redisUtil.hset(key, sceneNum, Objects.isNull(viewCount) ? "0" : String.valueOf(viewCount));
}
}finally {
redisLockUtil.unlockLua(lockKey, lockVal);
}
}
redisUtil.hincr(key, sceneNum, 1);
return ResultData.ok();
}
@Override
public ResultData uploadShareLogo(String num, MultipartFile file) throws Exception {
ScenePlus scenePlus = this.getScenePlusByNum(num);
if (Objects.isNull(scenePlus)) {
return ResultData.error(ErrorCode.FAILURE_CODE_5005);
}
ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByScenePlusId(scenePlus.getId());
String bucket = scenePlusExt.getYunFileBucket();
String fileName = file.getOriginalFilename();
String extName = fileName.substring(fileName.lastIndexOf("."));
File newFile = File.createTempFile(UUID.randomUUID().toString() ,extName);
file.transferTo(newFile);
String logoPath = newFile.getPath();
String outPathZh = ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+num+".png";
String outPathEn = ConstantFilePath.BASE_PATH + File.separator + "sceneQRcode/"+num+"_en.png";
String webSize = mainUrl + "/" + sceneProNewUrl + num;
QrCodeUtil.generate(webSize, QrConfig.create().setImg(logoPath).setWidth(1024).setHeight(1024), FileUtil.file(outPathZh));
QrCodeUtil.generate(webSize + "&lang=en", QrConfig.create().setImg(logoPath).setWidth(1024).setHeight(1024), FileUtil.file(outPathEn));
//上传logo图片
String ossLogoPath = String.format(UploadFilePath.DOWNLOADS_QRCODE, num) + "shareLogo" + extName;
ossUtil.uploadFile(bucket, ossLogoPath, logoPath, false);
//上传二维码
ossUtil.uploadFile(bucket, String.format(UploadFilePath.DOWNLOADS_QRCODE, num) + num + ".png", outPathZh, false);
ossUtil.uploadFile(bucket,String.format(UploadFilePath.DOWNLOADS_QRCODE, num) + num + "_en.png", outPathEn, false);
sceneEditInfoExt.setShareLogoImg(ossLogoPath);
sceneEditInfoExtService.updateById(sceneEditInfoExt);
FileUtil.del(newFile);
FileUtil.del(new File(outPathEn));
FileUtil.del(new File(outPathZh));
return ResultData.ok();
}
/**
*
* 初始化场景数据
*
* @author dengsixing
* @date 2022/8/22
* @param num 场景码
* @param title 场景标题
* @param des 场景描述
* @param sceneSource 场景来源:相机拍摄10以内表示,1表示八目,2双目,3转台,4 激光 其他来源10以上,11:一键换装,12:123看房,13文通虚拟场景
* @param dataSource 场景计算数据目录
* @param sceneScheme 方案:1-双目,2-转台,3-六目,4-八目,10-获取4k图,11-获取2k,12-获取1k
* @param sceneResolution 分辨率(2k,4k)
* @param sceneFrom 场景来源,lite:双目lite相机,pro:八目相机,minion:双面转台相机,laser:激光相机,virtual:虚拟场景,sketch:图片建模场景
* @return com.fdkankan.web.response.ResultData
**/
@Override
public ResultData initScene(String bucket, String num, String title, String des, Integer sceneSource,
String dataSource, Integer sceneScheme, String sceneResolution, String sceneFrom, String mdoelKind) {
ScenePlus scenePlus = this.getScenePlusByNum(num);
JSONObject fdageData = getFdageData(dataSource + File.separator + "capture" +File.separator+"data.fdage");
Integer videoVersion = fdageData.getInteger("videoVersion");
int cameraType = 10;//默认看看相机
if(sceneSource == 4 || sceneSource == 5){
cameraType = 14;
}
//生成场景主表
if(Objects.isNull(scenePlus)){
scenePlus = new ScenePlus();
}
scenePlus.setNum(num);
scenePlus.setSceneStatus(SceneStatus.SUCCESS.code());
scenePlus.setSceneSource(sceneSource);
scenePlus.setPayStatus(PayStatus.PAY.code());
scenePlus.setSceneType(SceneType.OTHER.code());
scenePlus.setTitle(title);
scenePlus.setDescription("" + fdageData.getString("info") + "
");
this.saveOrUpdate(scenePlus);
//生成场景拓展表
ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
if(Objects.isNull(scenePlusExt)){
scenePlusExt = new ScenePlusExt();
}
scenePlusExt.setPlusId(scenePlus.getId());
scenePlusExt.setDataSource(dataSource);
scenePlusExt.setSceneScheme(sceneScheme);
scenePlusExt.setSceneResolution(sceneResolution);
scenePlusExt.setSceneFrom(sceneFrom);
scenePlusExt.setModelKind(mdoelKind);
scenePlusExt.setSceneKind(SceneKind.FACE.code());
scenePlusExt.setYunFileBucket(bucket);
scenePlusExt.setAlgorithmTime(Calendar.getInstance().getTime());
scenePlusExt.setVideos(this.getVideosJson(dataSource, videoVersion, num, cameraType).toJSONString());
scenePlusExtService.saveOrUpdate(scenePlusExt);
//生成编辑主表
SceneEditInfo sceneEditInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
if(Objects.isNull(sceneEditInfo)){
sceneEditInfo = new SceneEditInfo();
}
sceneEditInfo.setScenePlusId(scenePlus.getId());
sceneEditInfo.setTitle(title);
sceneEditInfo.setDescription(des);
sceneEditInfoService.saveOrUpdate(sceneEditInfo);
sceneEditInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
//生成编辑拓展表
SceneEditInfoExt sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
if(Objects.isNull(sceneEditInfoExt)){
sceneEditInfoExt = new SceneEditInfoExt();
}
sceneEditInfoExt.setScenePlusId(scenePlus.getId());
sceneEditInfoExt.setEditInfoId(sceneEditInfo.getId());
sceneEditInfoExtService.save(sceneEditInfoExt);
sceneEditInfoExt = sceneEditInfoExtService.getByEditInfoId(sceneEditInfo.getId());
//生成编辑显示控制表
SceneEditControls sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
if(Objects.isNull(sceneEditControls)){
sceneEditControls = new SceneEditControls();
}
sceneEditControls.setEditInfoId(sceneEditInfo.getId());
sceneEditControls.setShowMap(0);
sceneEditControlsService.save(sceneEditControls);
sceneEditControls = sceneEditControlsService.getBySceneEditId(sceneEditInfo.getId());
//生成sceneJson
SceneJsonBean sceneJson = new SceneJsonBean();
BeanUtil.copyProperties(sceneEditInfoExt, sceneJson);
BeanUtil.copyProperties(sceneEditInfo, sceneJson);
SceneEditControlsVO sceneEditControlsVO = BeanUtil.copyProperties(sceneEditControls, SceneEditControlsVO.class);
sceneJson.setControls(sceneEditControlsVO);
sceneJson.setNum(num);
sceneJson.setCreateTime(scenePlus.getCreateTime());
sceneJson.setSceneResolution(scenePlusExt.getSceneResolution());
sceneJson.setSceneFrom(scenePlusExt.getSceneFrom());
sceneJson.setSceneKind(scenePlusExt.getSceneKind());
if(StrUtil.isNotEmpty(scenePlusExt.getVideos())){
sceneJson.setVideos(scenePlusExt.getVideos());
}
sceneJson.setModelKind(scenePlusExt.getModelKind());
//本地写sceneJson文件
String sceneJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH+"scene.json", num);
ossUtil.uploadFileBytes(bucket, sceneJsonPath, JSON.toJSONString(sceneJson).getBytes(StandardCharsets.UTF_8));
//生成floorplan.json
String floorPlanCardFilePath = dataSource + File.separator + "results/floorplan_cad.json";
if (new File(floorPlanCardFilePath).exists()) {
JSONObject json = FloorPlanUserUtil.createFloorPlanUserJson(floorPlanCardFilePath);
if(!Objects.isNull(json)){
String hourseTypeJsonPath = String.format(UploadFilePath.DATA_VIEW_PATH, num) + "floorplan.json";
ossUtil.uploadFileBytes(bucket, hourseTypeJsonPath, json.toJSONString().getBytes());
}
}
redisUtil.del(String.format(RedisKey.SCENE_JSON, num));
return ResultData.ok();
}
private JSONObject getFdageData(String dataFdagePath) {
log.info("dataFdagePath 文件路径 :{}", dataFdagePath);
String data = FileUtils.readFile(dataFdagePath);
//获取data.fdage的内容
JSONObject dataJson = new JSONObject();
if(data!=null){
dataJson = JSONObject.parseObject(data);
}
return dataJson;
}
private JSONObject getVideosJson(String path, Integer videoVersion, String projectNum, int cameraType){
//读取videos_hdr_param.json, 保存点位视频的value
Map videoMap = new HashMap<>();
String videosHdr = FileUtils.readFile(path + File.separator + "results/videos/videos_hdr_param.json");
JSONArray videoArray = null;
if(StringUtils.isNotEmpty(videosHdr)){
videoArray = JSONObject.parseObject(videosHdr).getJSONArray("hdr_param");
}
if(videoArray != null){
for(int i = 0, len = videoArray.size(); i < len; i++) {
videoMap.put(videoArray.getJSONObject(i).getString("name"), videoArray.getJSONObject(i).getString("value"));
if(videoArray.getJSONObject(i).containsKey("fov")){
videoMap.put(videoArray.getJSONObject(i).getString("name") + "_fov", videoArray.getJSONObject(i).getString("fov"));
}
}
}
//获取upload中的video视频名称
String uploadData = FileUtils.readFile(path + File.separator + "results" +File.separator+"upload.json");
JSONObject uploadJson = null;
JSONArray array = null;
if(uploadData!=null) {
uploadJson = JSONObject.parseObject(uploadData);
array = uploadJson.getJSONArray("upload");
}
JSONObject fileJson = null;
String fileName = "";
//计算ts文件的大小,并拼接成json格式
JSONArray jsonArray = new JSONArray();
JSONObject videoJson = null;
JSONObject videosJson = new JSONObject();
long videoSize = 0L;
for(int i = 0, len = array.size(); i < len; i++) {
fileJson = array.getJSONObject(i);
fileName = fileJson.getString("file");
if(fileJson.getIntValue("clazz") == 11 && fileName.contains(".mp4") && !fileName.contains("-ios.mp4")){
videoJson = new JSONObject();
videoJson.put("id", fileName.substring(
0, fileName.lastIndexOf(".")).replace("videos/", ""));
//如果ts文件存在,就计算ts大小
if(new File(path + File.separator + "results" +File.separator+ fileName.replace(".mp4", ".ts")).exists()){
videoSize = new File(path + File.separator + "results" +File.separator+ fileName.replace(".mp4", ".ts")).length();
videoJson.put("tsSize", videoSize);
}
if(videoMap.containsKey(videoJson.get("id"))){
videoJson.put("value", videoMap.get(videoJson.get("id")));
}
if(videoMap.containsKey(videoJson.get("id") + "_fov")){
videoJson.put("blend_fov", videoMap.get(videoJson.get("id") + "_fov"));
}else {
videoJson.put("blend_fov", 7);
}
jsonArray.add(videoJson);
}
}
videosJson.put("data", jsonArray);
if(Objects.nonNull(videoVersion) && videoVersion >= 4){
videosJson.put("version", 3);
videosJson.put("upPath", String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "Up.xml");
if(cameraType == 13){
//转台相机
videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
}
}else {
videosJson.put("version", 1);
videosJson.put("upPath", String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "Up2.xml");
if(cameraType == 13){
//转台相机
videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
}
}
if(cameraType == 5 || cameraType == 6){
videosJson.put("version", 1);
videosJson.put("upPath", String.format(UploadFilePath.DATA_VIEW_PATH, projectNum) + "stitch_params.txt");
}
return videosJson;
}
@Override
public ResultData editScene(LaserSceneBean param) {
ScenePlus scenePlus = this.getScenePlusByNum(param.getNum());
if(Objects.isNull(scenePlus))
throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
SceneEditInfo sceneEditInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
sceneEditInfo.setTitle(param.getTitle());
if(StrUtil.isEmpty(sceneEditInfo.getEntry())){
sceneEditInfo.setEntry("{}");
}
sceneEditInfoService.updateById(sceneEditInfo);
if (StrUtil.isNotBlank(param.getThumb())){
ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(scenePlus.getId());
String bucket = scenePlusExt.getYunFileBucket();
scenePlusExt.setThumb(param.getThumb());
scenePlusExtService.updateById(scenePlusExt);
File sourceFile=FileUtil.file(FdkkLaserConfig.getProfile(bucket)+param.getThumb());
log.info("sourceFile,-{}",sourceFile.getAbsoluteFile());
File targetFile=FileUtil.file(FdkkLaserConfig.getProfile(bucket)+String.format(UploadFilePath.USER_EDIT_PATH, param.getNum())+ File.separator+"thumb-1k.jpg");
log.info("targetFile,-{}",targetFile.getAbsoluteFile());
FileUtils.copyFile(sourceFile,targetFile);
}
return ResultData.ok();
}
@Override
public List listCleanOrigScene(int cleanOrigMonth) {
Date time = Calendar.getInstance().getTime();
time = DateUtil.beginOfDay(DateUtil.offset(time, DateField.MONTH, -cleanOrigMonth));
return this.baseMapper.selectCleanOrigScene(time);
}
@Override
public List getListByNums(List numList) {
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();
wrapper.in(ScenePlus::getNum,numList);
return this.list(wrapper);
}
@Override
public void deleteByList(List plusList,Long userId) throws FileSystemException {
HashMapcameraMap = new HashMap<>();
if(CollUtil.isEmpty(plusList)){
return;
}
List plusIds = plusList.parallelStream().map(ScenePlus::getId).collect(Collectors.toList());
HashMap plusMap = scenePlusExtService.getByPlusIds(plusIds);
for (ScenePlus scenePlus : plusList) {
if(scenePlus.getCameraId()!= null && plusMap.get(scenePlus.getId())!=null){
cameraMap.merge(scenePlus.getCameraId(), plusMap.get(scenePlus.getId()).getSpace(), Long::sum);
}
sceneDelLogService.saveLog(scenePlus.getNum(),userId);
}
//删除编辑和展示文件
for (ScenePlus plus : plusList) {
ScenePlusExt scenePlusExt = scenePlusExtService.getScenePlusExtByPlusId(plus.getId());
String bucket = scenePlusExt.getYunFileBucket();
ossUtil.deleteObject(bucket, String.format(UploadFilePath.VIEW_PATH, plus.getNum()));
ossUtil.deleteObject(bucket, String.format(UploadFilePath.EDIT_PATH, plus.getNum()));
}
scenePlusService.removeByIds(plusIds);
scenePlusExtService.removeByPlusIds(plusIds);
//删除原始资源文件
for (Long key : plusMap.keySet()) {
ScenePlusExt ext = plusMap.get(key);
if(StrUtil.isNotEmpty(ext.getDataSource()) && ext.getDataSource().length() > 5){
FileUtil.del(ext.getDataSource());
}
}
}
}