package com.fdkankan.scene.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.*;
import com.fdkankan.common.util.ConvertCommonUtils;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.common.util.WeiXinUtils;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.constant.RedisLockKey;
import com.fdkankan.redis.util.RedisLockUtil;
import com.fdkankan.scene.entity.Scene;
import com.fdkankan.scene.entity.SceneExt;
import com.fdkankan.scene.mapper.ISceneMapper;
import com.fdkankan.scene.service.ISceneAppService;
import com.fdkankan.scene.service.ISceneExtService;
import com.fdkankan.scene.service.ISceneService;
import com.fdkankan.scene.vo.SceneEditParamVO;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 八目场景编码表 服务实现类
 * </p>
 *
 * @author dengsixing
 * @since 2021-12-23
 */
@Slf4j
@Service
public class SceneAppServiceImpl extends ServiceImpl<ISceneMapper, Scene> implements ISceneAppService {

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

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

    @Autowired
    @Qualifier("uploadToOssUtil")
    UploadToOssUtil uploadToOssUtil;
    @Autowired
    ISceneService sceneService;
    @Autowired
    ISceneExtService sceneExtService;
    @Autowired
    RedisLockUtil redisLockUtil;


    @Override
    public int saveInitialPage(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getNum()) || StrUtil.isEmpty(base.getInitialPoint())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if(Objects.isNull(scene)){
            return -2;
        }
        SceneExt sceneExt = sceneExtService.getBySceneId(scene.getId());

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);
        StringBuffer imagesBuf = new StringBuffer()
                .append("images").append(File.separator)
                .append("images").append(scene.getNum())
                .append(File.separator);

        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());
        StringBuffer imagesBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(imagesBuf.toString());

        String path1 = imagesBuffer.append("thumbBigImg.jpg").toString();
        String path2 = imagesBuffer.append("thumbSmallImg.jpg").toString();

        //生成缩略图
        //按指定大小把图片进行缩和放（会遵循原图高宽比例）
        //此处把图片压成1024×512的缩略图
        Thumbnails.of(path1).size(1024,512).toFile(path2);//变为1024×512

        Map map = new HashMap();
        map.put("entry", JSONObject.parseObject(base.getInitialPoint()));
        map.put("thumbImg", 1);
        map.put("version", scene.getVersion()+1);
        FileUtils.writeJsonFile(dataBuffer.toString() + "scene.json", map);

        Map<String,String> uploadMap = new HashMap<String,String>();
        map.put(imagesBuffer.append("thumbBigImg.jpg").toString(), imagesBuf.append("thumbBigImg.jpg").toString());
        map.put(imagesBuffer.append("thumbFishBigImg.jpg").toString(), imagesBuf.append("thumbFishBigImg.jpg").toString());
        map.put(imagesBuffer.append("thumbSmallImg.jpg").toString(), imagesBuf.append("thumbSmallImg.jpg").toString());
        map.put(imagesBuffer.append("smallPic.jpg").toString(), imagesBuf.append("smallPic.jpg").toString());
        map.put(dataBuffer.toString() + "scene.json", dataBuf.toString() + "scene.json");

        uploadToOssUtil.uploadMulFiles(uploadMap);

        sceneExt.setEntry(base.getInitialPoint());
        scene.setThumbStatus(1);
        scene.setThumb(prefixAli + imagesBuf.append("thumbSmallImg.jpg").toString());
        if("aws".equals(type)){
            scene.setThumb(ConstantUrl.PREFIX_AWS + imagesBuf.append("thumbSmallImg.jpg").toString());
        }
        scene.setVersion(scene.getVersion() + 1);
        scene.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(scene);

        sceneExt.setUpdateTime(Calendar.getInstance().getTime());
        sceneExtService.updateById(sceneExt);

        return 1;
    }

    @Override
    public int saveFloorLogo(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getNum()) || StrUtil.isEmpty(base.getSize()) ||
                StrUtil.isEmpty(base.getLogoType())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if(scene == null){
            return -2;
        }

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);

        StringBuffer imagesBuf = new StringBuffer()
                .append("images").append(File.separator)
                .append("images").append(scene.getNum())
                .append(File.separator);

        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());
        StringBuffer imagesBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(imagesBuf.toString());

        Map map = new HashMap();
        map.put("floorLogo", base.getLogoType());
        map.put("floorLogoSize", base.getSize());
        map.put("version", scene.getVersion()+1);

        FileUtils.writeJsonFile(dataBuffer.toString() + "scene.json", map);

        scene.setFloorLogo(base.getLogoType());
        scene.setFloorLogoSize(Integer.parseInt(base.getSize()));
        scene.setVersion(scene.getVersion() + 1);
        scene.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(scene);

        uploadToOssUtil.upload(imagesBuffer.append("floorLogoImg.png").toString(), imagesBuf.append("floorLogoImg.png").toString());
        uploadToOssUtil.upload(dataBuffer.toString() + "scene.json", dataBuf.toString() + "scene.json");

        return 1;
    }

    @Override
    public int saveHot(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getType())){
            return -102;
        }

        String sid = base.getSid();

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if (scene == null ) {
            return -2;
        }
        SceneExt sceneExt = sceneExtService.getBySceneId(scene.getId());

        JSONObject jsonhot = JSONObject.parseObject(base.getHotData());

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);
        StringBuffer imagesBuf = new StringBuffer()
                .append("images").append(File.separator)
                .append("images").append(scene.getNum())
                .append(File.separator);

        StringBuffer imagesBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(imagesBuf.toString());
        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());

        String str = FileUtils.readFile(dataBuffer.toString() + "hot.json");
        JSONArray jsonhots = null;
        if (StringUtils.isNotEmpty(str)) {
            jsonhots = JSONArray.parseArray(str);
        }else {
            File file = new File(dataBuffer.toString() + "hot.json");
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            if(!file.exists()){
                file.createNewFile();
            }
        }

        String hotsids = "";
        //添加或者修改
        if("1".equals(base.getType())){
            sid = jsonhot.getString("sid");
            if(StrUtil.isEmpty(sid)){
                return -102;
            }
            jsonhots.add(jsonhot);
        }
        else if("0".equals(base.getType())){
            sid = jsonhot.getString("sid");
            if(StrUtil.isEmpty(sid)){
                return -102;
            }
        }
        else if("-1".equals(base.getType())){
            if(StrUtil.isEmpty(sid)){
                return -102;
            }
        }


        for(int i=0;i<jsonhots.size();++i) {
            JSONObject ele = jsonhots.getJSONObject(i);
            hotsids += ele.getString("sid") +",";
            if(ele.getString("sid").equals(sid)) {
                if("-1".equals(base.getType())) {
                    jsonhots.remove(i);
                    jsonhot = ele;
                }
                else if("0".equals(base.getType())) {
                    jsonhots.set(i, jsonhot);

                }
            }
        }

        Map<String,String> map = new HashMap<String,String>();
        if(jsonhot.containsKey("media")) {
            String fileType = jsonhot.getString("media");
            if(fileType.contains("photo")) {
                if("-1".equals(base.getType())) {
                    FileUtils.deleteFile(imagesBuffer.append("hot").append(sid).append(".jpg").toString());
                }
                else {
                    map.put(imagesBuffer.append("hot").append(sid).append(".jpg").toString(), imagesBuf.append("hot").append(sid).append(".jpg").toString());
                }
            }
            if(fileType.contains("audio")) {
                if("-1".equals(base.getType())) {
                    FileUtils.deleteFile(imagesBuffer.append("hot").append(sid).append(".mp3").toString());
                }
                else {
                    map.put(imagesBuffer.append("hot").append(sid).append(".mp3").toString(), imagesBuf.append("hot").append(sid).append(".mp3").toString());
                }
            }
            if(fileType.contains("video")) {
                if("-1".equals(base.getType())) {
                    FileUtils.deleteFile(imagesBuffer.append("hot").append(sid).append(".mp4").toString());
                }
                else
                {
                    map.put(imagesBuffer.append("hot").append(sid).append(".mp4").toString(), imagesBuf.append("hot").append(sid).append(".mp4").toString());
                }
            }
        }

        FileUtils.deleteFile(dataBuffer.toString() + "hot.json");
        File dataPath = new File(dataBuffer.toString());
        if(!dataPath.exists()){
            dataPath.mkdirs();
        }
        FileUtils.writeFile(dataBuffer.toString() + "hot.json", jsonhots.toString());

        map.put(dataBuffer.toString() + "hot.json", dataBuf.toString() + "hot.json");
        uploadToOssUtil.uploadMulFiles(map);

        scene.setVersion(scene.getVersion() + 1);
        scene.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(scene);

        sceneExt.setHotsIds(hotsids);
        sceneExt.setUpdateTime(Calendar.getInstance().getTime());
        sceneExtService.updateById(sceneExt);

        String strsceneInfos = FileUtils.readFile(dataBuffer.toString() + "scene.json");
        JSONObject scenejson = new JSONObject();
        if(strsceneInfos!=null){
            scenejson = JSONObject.parseObject(strsceneInfos);
        }
        if(jsonhots.size()>0){
            scenejson.put("hots", 1);
        }
        else{
            scenejson.put("hots", 0);
        }
        FileUtils.writeFile(dataBuffer.toString() + "scene.json", scenejson.toString());

        return 1;
    }

    @Override
    public int saveBackgroundMusic(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getNum()) || StrUtil.isEmpty(base.getMusicName())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if(scene == null){
            return -2;
        }
        SceneExt sceneExt = sceneExtService.getBySceneId(scene.getId());

        JSONObject jsonhot = JSONObject.parseObject(base.getHotData());
        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);

        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());

        Map map = new HashMap();
        map.put("bgMusic", base.getMusicName());
        map.put("version", scene.getVersion()+1);

        FileUtils.writeJsonFile(dataBuffer.toString() + "scene.json", map);

        scene.setVersion(scene.getVersion() + 1);
        scene.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(scene);

        sceneExt.setBgMusic(base.getMusicName());
        sceneExt.setUpdateTime(Calendar.getInstance().getTime());
        sceneExtService.updateById(sceneExt);

        return 1;
    }

    @Override
    public int saveSceneInfo(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getNum()) || StrUtil.isEmpty(base.getSceneName()) ||
                StrUtil.isEmpty(base.getSceneType()) || StrUtil.isEmpty(base.getSceneDec())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if(scene == null){
            return -2;
        }

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);

        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());

        Map map = new HashMap();
        map.put("sceneName", base.getSceneName());
        map.put("sceneDec", base.getSceneDec());
        map.put("sceneType", base.getSceneType());
        if(base.getSceneKey() != null){
            map.put("sceneKey", base.getSceneKey());
        }
        map.put("version", scene.getVersion()+1);

        FileUtils.writeJsonFile(dataBuffer.toString() + "scene.json", map);

        scene.setSceneName(base.getSceneName());
        scene.setSceneDec(base.getSceneDec());
        scene.setSceneType(Integer.parseInt(base.getSceneType()));
        scene.setSceneKey(base.getSceneKey());
        scene.setVersion(scene.getVersion() + 1);
        scene.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(scene);

        return 1;
    }

    @Override
    public int saveSceneKey(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getNum()) || StrUtil.isEmpty(base.getSceneKey())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if(scene == null){
            return -2;
        }

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);

        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());


        Map map = new HashMap();
        map.put("sceneKey", base.getSceneKey());
        map.put("version", scene.getVersion()+1);

        FileUtils.writeJsonFile(dataBuffer.toString() + "scene.json", map);

        scene.setSceneKey(base.getSceneKey());
        scene.setVersion(scene.getVersion() + 1);
        scene.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(scene);

        return 1;
    }

    @Override
    public int saveTourList(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getNum()) || StrUtil.isEmpty(base.getTourList())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if(scene == null){
            return -2;
        }
        SceneExt sceneExt = sceneExtService.getBySceneId(scene.getId());

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);

        StringBuffer imagesBuf = new StringBuffer()
                .append("images").append(File.separator)
                .append("images").append(scene.getNum())
                .append(File.separator);

        StringBuffer imagesBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(imagesBuf.toString());
        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());

        Map<String,String> map = new HashMap<String,String>();

        log.info("editForApp/saveTourList：生成tourList.json文件");
        String tourListPath = dataBuffer.toString() + ConstantFileName.TOUR_LIST;
        FileUtils.writeFile(tourListPath, base.getTourList());
        map.put(tourListPath, dataBuf.toString() + ConstantFileName.TOUR_LIST);

        JSONArray tourJsons = JSONArray.parseArray(base.getTourList());

        String path = imagesBuffer.append(ConstantFileName.TOURLIST_FOLDER).toString();

        for(int i=0;i<tourJsons.size();++i)
        {
            String fileName = path + File.separator +"guide"+i+".jpg";
            map.put(fileName, imagesBuf.append(ConstantFileName.TOURLIST_FOLDER).append(File.separator).append("guide").append(i).append(".jpg").toString());
        }

        File file = new File(dataBuffer.toString() + ConstantFileName.TOURLIST_FOLDER);
        String[] strs = file.list();
        if(strs!=null) {
            int screencapLen = 0;
            for(int i=0;i<strs.length;++i)
            {
                if(strs[i].indexOf(ConstantFileName.SCREEN_CRP_DATAFILE)>-1)
                {
                    map.put(dataBuffer.toString() + ConstantFileName.TOURLIST_FOLDER + File.separator + strs[i], dataBuf.toString() + ConstantFileName.TOURLIST_FOLDER + File.separator + strs[i]);
                    ++screencapLen;
                }
            }

            Map<String, Object> jsonMap = new HashMap();
            jsonMap.put("screenCapLen", screencapLen);
            jsonMap.put("version", scene.getVersion() + 1);

            FileUtils.writeJsonFile(dataBuffer.toString() + "scene.json", jsonMap);

            scene.setVersion(scene.getVersion() + 1);
            scene.setUpdateTime(Calendar.getInstance().getTime());
            this.updateById(scene);

            sceneExt.setScreencapLen(screencapLen);
            sceneExt.setUpdateTime(Calendar.getInstance().getTime());
            sceneExtService.updateById(sceneExt);
        }

        uploadToOssUtil.uploadMulFiles(map);

        return 1;
    }


    @Override
    public Object uploadPic(String sceneNum, String folderName, MultipartFile file) throws IOException {
        if(StrUtil.isEmpty(sceneNum)){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(sceneNum);
        if(scene == null){
            return -2;
        }

        if (file.isEmpty() && file.getSize() <= 0) {
            return -99;
        }

        String lockKey = String.format(RedisLockKey.LOCK_UPLOAD_PIC, sceneNum);
//        Boolean lock = redisTemplate.opsForValue()
//                                    .setIfAbsent(lockKey, Thread.currentThread().getId(), RedisKey.EXPIRE_TIME_10_MINUTE, TimeUnit.MILLISECONDS);
        Boolean lock = redisLockUtil.lock(lockKey, RedisKey.EXPIRE_TIME_10_MINUTE);

        if(!lock){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5036);
        }

        File targetFile = null;

        try {
            //文件上传的位置可以自定义
            String path = ConstantFilePath.SCENE_PATH+"images"+File.separator+"images"+sceneNum;
            if(StrUtil.isNotEmpty(folderName)) {
                path = path+File.separator + folderName;
            }
            targetFile = new File(path);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            targetFile = new File(path + File.separator + fileName);
            // 保存
            if(targetFile.exists())
            {
                FileUtils.deleteFile(path + File.separator + fileName);
            }
            file.transferTo(targetFile);
        }catch (Exception e){
            log.error("上传图片失败", e);
            throw new BusinessException(ErrorCode.FAILURE_CODE_5037);
        }finally {
            redisLockUtil.unlock(lockKey);
        }

        return targetFile.getName();
    }

    @Override
    public Object uploadScreencapVoice(String sceneNum, MultipartFile file) throws IOException {
        if(StrUtil.isEmpty(sceneNum)){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(sceneNum);
        if(scene == null){
            return -2;
        }
        SceneExt sceneExt = sceneExtService.getBySceneId(scene.getId());

        if(file.isEmpty() && file.getSize() <= 0) {
            return -99;
        }

        String lockKey = String.format(RedisLockKey.LOCK_UPLOAD_VOICE, sceneNum);
        Boolean lock = redisLockUtil.lock(lockKey, RedisKey.EXPIRE_TIME_30_MINUTE);

        if(!lock){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5036);
        }

        String originalFileName = null;
        try {
            //文件上传的位置可以自定义
            String path = ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+sceneNum;
            File targetFile = new File(path);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            originalFileName = file.getOriginalFilename();
            targetFile = new File(path + File.separator +originalFileName);
            // 保存
            if(targetFile.exists())
            {
                FileUtils.deleteFile(path + File.separator + originalFileName);
            }
            file.transferTo(targetFile);

            uploadToOssUtil.upload(path + File.separator +originalFileName, "voice/voice"+sceneNum+"/"+originalFileName);

            Map map = new HashMap();
            map.put("screencapVoiceFileName", originalFileName);
            String voiceSrc = prefixAli + "voice/voice"+sceneNum+"/"+originalFileName;
            if("aws".equals(type)){
                voiceSrc = ConstantUrl.PREFIX_AWS + "voice/voice"+sceneNum+"/"+originalFileName;
            }
            map.put("screencapVoiceSrc", voiceSrc);
            map.put("version", scene.getVersion()+1);
            FileUtils.writeJsonFile(ConstantFilePath.SCENE_PATH + "data/data" + sceneNum + "/scene.json", map);

            scene.setVersion(scene.getVersion() + 1);
            scene.setUpdateTime(Calendar.getInstance().getTime());
            this.updateById(scene);

            sceneExt.setScreencapVoiceSrc(voiceSrc);
            sceneExt.setUpdateTime(Calendar.getInstance().getTime());
            sceneExtService.updateById(sceneExt);

        }catch (Exception e){
            log.error("上传图片失败", e);
            throw new BusinessException(ErrorCode.FAILURE_CODE_5040);
        }finally {
            redisLockUtil.unlock(lockKey);
        }

        return originalFileName;
    }

    @Override
    public int saveScreencapFile(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getNum()) || StrUtil.isEmpty(base.getIndex()) ||
                StringUtils.isEmpty(base.getCamerasData())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if(scene == null){
            return -2;
        }
        SceneExt sceneExt = sceneExtService.getBySceneId(scene.getId());

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);

        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());

        if("1".equals(base.getIndex())){
            File file = new File(dataBuffer.toString() + ConstantFileName.TOURLIST_FOLDER);
            if(file.isDirectory()){
                String[] strs = file.list();
                if(strs!=null){
                    for(int i=0;i<strs.length;++i) {

                        if(strs[i].indexOf(ConstantFileName.SCREEN_CRP_DATAFILE)>-1) {
                            FileUtils.deleteFile(dataBuffer.toString() + ConstantFileName.TOURLIST_FOLDER + File.separator + strs[i]);
                        }
                    }
                }
            } else {
                file.mkdirs();
            }

            Map<String, Object> map = new HashMap<>();
            map.put("screencapLen", "0");
            map.put("version", scene.getVersion()+1);
            FileUtils.writeJsonFile(dataBuffer.toString() + "scene.json", map);

            scene.setVersion(scene.getVersion() + 1);
            scene.setUpdateTime(Calendar.getInstance().getTime());
            this.updateById(scene);

            sceneExt.setScreencapLen(0);
            sceneExt.setUpdateTime(Calendar.getInstance().getTime());
            sceneExtService.updateById(sceneExt);
        }

        String filePath = dataBuffer.toString() + ConstantFileName.TOURLIST_FOLDER + File.separator + ConstantFileName.SCREEN_CRP_DATAFILE + base.getIndex() + ".json";
        File file = new File(filePath);
        if(!file.exists())
        {
            log.info("创建文件：" + filePath);
            file.createNewFile();
        }
        FileUtils.writeFile(filePath, base.getCamerasData());

        return 1;
    }

    @Override
    public int saveHotVisible(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getData())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if (scene == null ) {
            return -2;
        }

        JSONArray visiblePanos = JSONArray.parseArray(base.getData());

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);
        StringBuffer imagesBuf = new StringBuffer()
                .append("images").append(File.separator)
                .append("images").append(scene.getNum())
                .append(File.separator);

        StringBuffer imagesBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(imagesBuf.toString());
        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());

        File file = new File(dataBuffer.toString() + "hot.json");
        if (!file.exists()) {
            return -99;
        }

        String str = FileUtils.readFile(dataBuffer.toString() + "hot.json");
        JSONArray hots = JSONArray.parseArray(str);
        for (int i = 0; i < hots.size(); ++i) {
            JSONObject hot = hots.getJSONObject(i);
            for (int j = 0; j < visiblePanos.size(); ++j) {
                if (hot.getString("sid").equals(((JSONObject) visiblePanos.get(j)).getString("sid"))) {
                    hot.put("visiblePanos", ((JSONObject) visiblePanos.get(j)).getJSONArray("value"));
                }
            }
        }

        scene.setVersion(scene.getVersion() + 1);
        this.updateById(scene);

        FileUtils.deleteFile(dataBuffer.toString() + "hot.json");
        FileUtils.writeFileContent(dataBuffer.toString() + "hot.json", hots.toString());

        uploadToOssUtil.upload(dataBuffer.toString() + "hot.json", dataBuf.toString() + "hot.json");
        return 1;
    }

    @Override
    public int saveLinkPano(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getData()) || StrUtil.isEmpty(base.getNum())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if (scene == null ) {
            return -2;
        }

        JSONArray inputData = JSONObject.parseArray(base.getData());

        StringBuffer dataBuf = new StringBuffer()
                .append("data").append(File.separator)
                .append("data").append(scene.getNum())
                .append(File.separator);
        StringBuffer imagesBuf = new StringBuffer()
                .append("images").append(File.separator)
                .append("images").append(scene.getNum())
                .append(File.separator);

        StringBuffer dataBuffer = new StringBuffer(ConstantFilePath.SCENE_PATH).append(dataBuf.toString());

        File directory = new File(dataBuffer.toString());
        if (!directory.exists()) {
            directory.mkdirs();
        }

        String modeldataUrl = prefixAli + imagesBuf.toString() + "vision.modeldata?t=" + System.currentTimeMillis();
        if("aws".equals(type)){
            modeldataUrl = ConstantUrl.PREFIX_AWS + imagesBuf.toString() + "vision.modeldata?t=" + System.currentTimeMillis();
        }
        FileUtils.downLoadFromUrl(modeldataUrl, "vision.modeldata", dataBuffer.toString());
        File file = new File(dataBuffer.toString() + "vision.modeldata");
        if(file.exists()) {
            return -1;
        }
        ConvertCommonUtils.convertVisionModelDataToTxt(dataBuffer.toString() + "vision.modeldata", dataBuffer.toString() + "vision.json");

        String str = FileUtils.readFile(dataBuffer.toString() + "vision.json");
        JSONObject json = JSONObject.parseObject(str);
        JSONArray panos = json.getJSONArray("sweepLocations");
        for (int i = 0; i < panos.size(); ++i) {
            JSONObject pano = panos.getJSONObject(i);
            for (int j = 0; j < inputData.size(); ++j) {
                JSONObject jo = inputData.getJSONObject(j);
                String currentPanoId = jo.getString("panoID");
                JSONArray visibles = jo.getJSONArray("visibles");
                JSONArray visibles3 = jo.getJSONArray("visibles3");
                if (pano.getString("uuid").equals(currentPanoId)) {
                    pano.put("visibles", visibles);
                    pano.put("visibles3", visibles3);
                }
            }
        }
        FileUtils.deleteFile(dataBuffer.toString() + "vision.json");
        FileUtils.deleteFile(dataBuffer.toString() + "vision.modeldata");
        FileUtils.writeFileContent(dataBuffer.toString() + "vision.json", json.toString());
        ConvertCommonUtils.convertTxtToVisionModelData(dataBuffer.toString() + "vision.json", dataBuffer.toString() + "vision.modeldata");
        uploadToOssUtil.upload(dataBuffer.toString() + "vision.modeldata", imagesBuf.toString() + "vision.modeldata");
        return 1;
    }

    @Override
    public Object getRecordAudioFromWeixin(SceneEditParamVO base) throws Exception {
        if(StrUtil.isEmpty(base.getData()) || StrUtil.isEmpty(base.getId())){
            return -102;
        }

        Scene scene = sceneService.getSceneBySceneCode(base.getNum());
        if (scene == null ) {
            return -2;
        }
        SceneExt sceneExt = sceneExtService.getBySceneId(scene.getId());

        String accessToken = WeiXinUtils.getAccessToken();

        InputStream is = null;
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+ accessToken + "&media_id=" + base.getId();
        URL urlGet = new URL(url);
        HttpURLConnection http = (HttpURLConnection) urlGet
                .openConnection();
        http.setRequestMethod("GET"); // 必须是get方式请求
        http.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        http.setDoOutput(true);
        http.setDoInput(true);
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
        http.connect();
        // 获取文件转化为byte流
        is = http.getInputStream();
        File dic = new File(ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum());
        if(!dic.exists())
        {
            dic.mkdirs();
        }
        File voice = new File(ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator+ConstantFileName.VOICE_NAME+".amr");
        if(voice.exists())
        {
            FileUtils.deleteFile(ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator+ConstantFileName.VOICE_NAME+".amr");
        }
        FileUtils.saveImageToDisk( accessToken,  base.getId(), ConstantFileName.VOICE_NAME, ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator, is);

        try
        {
            FileUtils.changeVoiceToMp3(ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator+ConstantFileName.VOICE_NAME+".amr",
                    ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator+ConstantFileName.VOICE_NAME+".mp3");
        }
        catch(Exception e)
        {
            StringWriter trace=new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            log.error("voice:"+ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator+ConstantFileName.VOICE_NAME+".amr");
            log.error(trace.toString());
            return -97;
        }
        String originalFileName = ConstantFileName.VOICE_NAME+".mp3";
        uploadToOssUtil.upload(ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator +originalFileName, "voice/voice"+base.getNum()+"/"+originalFileName);

        Map map = new HashMap();
        map.put("screencapVoiceFileName", originalFileName);
        String voiceSrc = prefixAli+"voice/voice"+base.getNum()+"/"+originalFileName;
        if("aws".equals(type)){
            voiceSrc = ConstantUrl.PREFIX_AWS+"voice/voice"+base.getNum()+"/"+originalFileName;
        }
        map.put("screencapVoiceSrc", voiceSrc);
        map.put("version", scene.getVersion()+1);
        FileUtils.writeJsonFile(ConstantFilePath.SCENE_PATH + "data/data" + base.getNum() + "/scene.json", map);

        scene.setVersion(scene.getVersion());
        scene.setUpdateTime(Calendar.getInstance().getTime());
        this.updateById(scene);

        sceneExt.setScreencapVoiceSrc(voiceSrc);
        sceneExt.setUpdateTime(Calendar.getInstance().getTime());
        sceneExtService.updateById(sceneExt);

        FileUtils.deleteFile(ConstantFilePath.SCENE_PATH+"voice"+File.separator+"voice"+base.getNum()+File.separator+ConstantFileName.VOICE_NAME+".amr");
        return originalFileName;
    }
}
