package com.fdkankan.scene.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.ConstantFilePath;
import com.fdkankan.common.constant.UploadFilePath;
import com.fdkankan.common.util.CreateObjUtil;
import com.fdkankan.common.util.FileUtil;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.common.util.SceneUtil;
import com.fdkankan.dingtalk.DingTalkSendUtils;
import com.fdkankan.fyun.oss.UploadToOssUtil;
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.constant.RedisKey;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.scene.service.IBuildSceneDTService;
import com.fdkankan.scene.service.IBuildScenePreService;
import com.fdkankan.scene.service.IScenePlusService;
import java.io.File;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/3/1
 **/
@Slf4j
@Service
public class BuildScenePreServiceImpl implements IBuildScenePreService {

    @Value("${oss.prefix.ali}")
    private String prefixAli;
    @Value("${model.timeOut:48}")
    private int modelTimeOut;
    @Value("${upload.type}")
    private String ossType;
    @Value("${environment:dev}")
    private String environment;
    @Value("${queue.modeling.modeling-call}")
    private String queueModelingCall;

    @Autowired
    UploadToOssUtil uploadToOssUtil;
    @Autowired
    private DingTalkSendUtils dingTalkSendUtils;
    @Autowired
    private IScenePlusService scenePlusService;
    @Autowired
    private PlatformUserClient platformUserClient;
    @Autowired
    private PlatformGoodsClient platformGoodsClient;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private RabbitMqProducer mqProducer;
    @Autowired
    private IBuildSceneDTService buildSceneDTService;

    public static String hostName;

    public static final String DINGTALK_MSG_PATTERN = "**环境**: %s\n\n" +
        "**服务器名称**: %s\n\n" +
        "**失败原因**: %s\n\n" +
        "**num**: %s\n\n" +
        "**server-path**: %s\n\n";
//        "**algorithm-log**: [https://4dkk.4dage.com/build_log/%s/console.log](https://4dkk.4dage.com/build_log/%s/console.log)";

    public static final String contentExt = "**algorithm-log**: [https://4dkk.4dage.com/build_log/%s/console.log](https://4dkk.4dage.com/build_log/%s/console.log)";

    @Value("${hostName.filePath:/opt/hosts/hosts.txt}")
    public void setHostName(String filePath){
        try {
            this.hostName = FileUtils.readFile(filePath);
            log.error("从文件({})中获取服务器名称:{}", filePath,hostName);
        } catch (Exception e) {
            log.error("从文件中获取服务器名称失败,文件路径{}", filePath);
            e.printStackTrace();
        }
    }


    @Override
    public void buildScenePre(BuildSceneCallMessage message) {
        boolean success = false;
        try {
            String key = String.format(RedisKey.SCENE_BUILDING, message.getSceneNum());
            Long building = redisUtil.incr(key, 1);
            if (building.compareTo(1L) != 0) {
                log.info("场景正在构建中,退出构建,参数：{}", JSONObject.toJSONString(message));
                return;
            } else {
                redisUtil.expire(key, Duration.of(modelTimeOut, ChronoUnit.HOURS));
            }

            //根据相机类型，组装资源路径
            String path = SceneUtil.getPath(message.getPath(), message.getCameraName(),
                message.getFileId(), Integer.parseInt(message.getCameraType()), message.getUnicode());

            //下载资源到本地
            this.downLoadSource(message, path);

            //发送mq，就进行计算
            mqProducer.sendByWorkQueue(queueModelingCall, message);

            success = true;

            log.info("场景计算资源准备结束，场景码：{}", message.getSceneNum());

        }catch (Exception e){
            log.error("场景计算前置处理出错", e);
        }finally {
            //如果前置处理失败，发送钉钉消息
            if(!success){
                String serverPath = message.getPath().substring(0,message.getPath().lastIndexOf("/")+1).concat(message.getPrefix());
//            buildSceneDTService.handFail("场景计算前置处理出错", serverPath, message.getSceneNum(), BuildScenePreServiceImpl.hostName, null);
            }

        }
    }

    @Override
    public Map<String, String> getTypeString(String cameraType, String algorithm, String resolution,
        JSONObject dataJson) {
        return null;
    }

    @Override
    public String getPath(BuildSceneCallMessage buildSceneMqMessage) throws Exception{
        String path = buildSceneMqMessage.getPath();
        String cameraName = buildSceneMqMessage.getCameraName();
        String fileId = buildSceneMqMessage.getFileId();
        int cameraType = Integer.parseInt(buildSceneMqMessage.getCameraType());
        String unicode = buildSceneMqMessage.getUnicode();
        if(cameraType < 3){
            return path;
        }
        String localPath = cameraName.replace("4DKKPRO_", "")
            .replace("-fdage", "").toLowerCase() +
            File.separator + fileId + File.separator + unicode;

        if(cameraType == 5 || cameraType == 6){
            path = ConstantFilePath.BUILD_MODEL_PATH + unicode;
        }else if(cameraType == 14) {
            path = ConstantFilePath.BUILD_MODEL_LASER_PATH + localPath;
        } else{
            path = ConstantFilePath.BUILD_MODEL_PATH + localPath;
        }
        return path;
    }

    @Override
    public void downLoadSource(BuildSceneCallMessage buildSceneMqMessage,String path) throws Exception{
        String cameraName = buildSceneMqMessage.getCameraName();
        String fileId = buildSceneMqMessage.getFileId();
        String unicode = buildSceneMqMessage.getUnicode();
        int cameraType = Integer.parseInt(buildSceneMqMessage.getCameraType());
        String prefix = buildSceneMqMessage.getPrefix();
        String imgsName = buildSceneMqMessage.getImgsName();
        if(cameraType < 3){
            for(int i = 0;i<5;++i){
                try{
                    FileUtils.downLoadFromUrl(prefix+imgsName+"?m="+new Date().getTime(), imgsName,
                        path + File.separator + "capture");
                    FileUtils.decompress(path + File.separator + "capture" +File.separator+imgsName,
                        path + File.separator + "capture") ;
                    break;
                }catch(Exception e){
                    log.error(String.format("第%d次下载并解压资源失败", i+1),  e);
                    if(i<4)
                    {
                        FileUtils.deleteFile(path + File.separator + "capture" +File.separator+imgsName);
                        FileUtils.delFolder(path + File.separator + "capture" +File.separator+"images");
                    }
                    Thread.sleep(10000);
                }
            }
            FileUtils.deleteFile(path + File.separator + "capture" +File.separator+"zip.Zip");
        }else{
            String ossPath = ConstantFilePath.OSS_PREFIX + cameraName.replace("4DKKPRO_", "")
                .replace("-fdage", "").toLowerCase() + File.separator + fileId + File.separator
                + unicode + File.separator;
            if(cameraType == 5 || cameraType == 6){
                path = ConstantFilePath.BUILD_MODEL_PATH + unicode;
                //下载zip包
                FileUtils.downLoadFromUrl(prefix + "/" + imgsName + "?m=" + System.currentTimeMillis(), imgsName, path + File.separator + "capture");
                //解压
                FileUtils.decompress(path + File.separator + "capture" + File.separator + imgsName,
                    path + File.separator + "capture") ;
                //删除压缩包
                FileUtil.delFile(path + File.separator + "capture" + File.separator + imgsName);
            }else if(cameraType == 14) {
                CreateObjUtil.ossUtilCp(ossPath,path + File.separator + "capture");
            } else{
                CreateObjUtil.ossUtilCp(ossPath,path + File.separator + "capture");
            }
        }
    }

//    @Override
//    public Map<String, String> uploadFileMapHandler(String num, int cameraType, Map<String, String> map) {
//        if(CollUtil.isEmpty(map)){
//            return null;
//        }
//
//        String dataPath = String.format("data/data%s/", num);
//        String imagePath = String.format("images/images%s/", num);
//        String videoPath = String.format("video/video%s/", num);
//
//        String dataViewPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
//        String imgViewPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
//        String videosViewPath = String.format(UploadFilePath.VIDEOS_VIEW_PATH, num);
//
//        Map<String, String> newMap = new HashMap<>();
//        for (String key : map.keySet()) {
//            String value = map.get(key);
//            if(value.contains(dataPath)){
//                newMap.put(key, value.replace(dataPath, dataViewPath));
//            }
//            if(value.contains(imagePath)){
//                newMap.put(key, value.replace(imagePath, imgViewPath));
//            }
//            if(value.contains(videoPath)){
//                newMap.put(key, value.replace(videoPath, videosViewPath));
//            }
//        }
////        map.entrySet().parallelStream().forEach(entry -> {
////            String key = entry.getKey();
////            String value = entry.getValue();
////            if(value.contains(dataPath)){
////                newMap.put(key, value.replace(dataPath, dataViewPath));
////            }
////            if(value.contains(imagePath)){
////                newMap.put(key, value.replace(imagePath, imgViewPath));
////            }
////            if(value.contains(videoPath)){
////                newMap.put(key, value.replace(videoPath, videosViewPath));
////            }
////        });
//        return newMap;
//    }

//    @Override
//    public void uploadCaches(String num, Map<String,String> map, String path){
//
//        String sceneNumPAth = String.format("scene/%s", num);
//
//        List<String> imagesList = FileUtil.getFileList(path + "/caches/images");
//        log.info("caches/images_path:{}", path + "/caches/images");
//        if(CollUtil.isNotEmpty(imagesList)){
//            log.info("上传的caches/images文件列表：{}", imagesList.toString());
//            imagesList.stream().forEach(str -> {
//                if(str.endsWith(".jpg")){
//                    map.put(str, str.replace(path, sceneNumPAth));
//                }
//            });
//        }
//
//        List<String> videosList = FileUtil.getFileList(path + "/caches/videos");
//        if(CollUtil.isNotEmpty(videosList)){
//            log.info("上传的caches/videos文件列表：{}", videosList.toString());
//            videosList.stream().forEach(str -> map.put(str, str.replace(path, sceneNumPAth)));
//        }
//    }

//    @Override
//    public void copyToEditDir(String num) throws IOException {
//
//        String editImagesPath = String.format(UploadFilePath.IMG_EDIT_PATH, num);
//        String viewImagesPath = String.format(UploadFilePath.IMG_VIEW_PATH, num);
//
//        String editDataPath = String.format(UploadFilePath.DATA_EDIT_PATH, num);
//        String viewDataPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
//
//        Map<String, String> map = new HashMap<>();
//        map.put(editImagesPath + "vision.modeldata", viewImagesPath + "vision.modeldata");
//        map.put(editImagesPath + "vision2.modeldata", viewImagesPath + "vision2.modeldata");
//        map.put(editDataPath + "floorplan_cad.json", viewDataPath + "floorplan_cad.json");
//
//        for (Entry<String, String> entry : map.entrySet()) {
//            uploadToOssUtil.copyFiles(entry.getValue(), entry.getKey());
//        }
//    }

//    @Override
//    public void sendSms(Integer pushChannel, String pushToken, int cameraType, String sceneName, String webSite){
//        log.info("推送消息，渠道是 {}, 手机token是 {}", pushChannel, pushToken);
//        if(Objects.isNull(pushChannel) && StrUtil.isBlank(pushToken))
//            return;
//
//        try{
//            if(StorageType.AWS.code().equals(ossType)){
//                PushMsgUtil.googlePushMsg(ConstantFilePath.BASE_PATH + "/refreshToken.json", pushToken,
//                    sceneName + "计算完成", "您上传的" + sceneName + "计算完成，点击查看", webSite);
//                return;
//            }
//
//            PushMessageConfig demo = null;
//            if(pushChannel == 0){
//                if(cameraType == 10 || cameraType == 13){
//                    //ios
//                    log.info("IOS_KEY:{}, IOS_SECRET:{}", IOS_KEY_Z, IOS_SECRET_Z);
//                    demo = new PushMessageConfig(IOS_KEY_Z, IOS_SECRET_Z);
//                    demo.sendIOSUnicast(pushToken,  "四维看看Minion",
//                        sceneName + "计算完成", "您上传的" + sceneName + "计算完成，点击查看", webSite);
//                }else {
//                    //ios
//                    log.info("IOS_KEY:{}, IOS_SECRET:{}", IOS_KEY, IOS_SECRET);
//                    demo = new PushMessageConfig(IOS_KEY, IOS_SECRET);
//                    demo.sendIOSUnicast(pushToken, "四维看看Pro",
//                        sceneName + "计算完成", "您上传的" + sceneName + "计算完成，点击查看", webSite);
//                }
//            }else {
//                if(cameraType == 10 || cameraType == 13){
//                    //ios
//                    //安卓
//                    log.info("ANDROID_KEY:{}, ANDROID_SECRET:{}", ANDROID_KEY_Z, ANDROID_SECRET_Z);
//                    demo = new PushMessageConfig(ANDROID_KEY_Z, ANDROID_SECRET_Z);
//                    demo.sendAndroidUnicast2(pushToken, "四维看看Minion",
//                        sceneName + "计算完成", "您上传的" + sceneName + "计算完成，点击查看", webSite);
//                }else {
//                    //安卓
//                    log.info("ANDROID_KEY:{}, ANDROID_SECRET:{}", ANDROID_KEY, ANDROID_SECRET);
//                    demo = new PushMessageConfig(ANDROID_KEY, ANDROID_SECRET);
//                    demo.sendAndroidUnicast(pushToken, "四维看看Pro",
//                        sceneName + "计算完成", "您上传的" + sceneName + "计算完成，点击查看", webSite);
//                }
//            }
//            log.info("消息推送结束！");
//        }catch (Exception e){
//            log.error("推送消息失败：", e);
//        }
//    }

//    @Override
//    public void handFail(String reason, String serverPath, String num, String hostName, String contentExt) {
//        CompletableFuture.runAsync(() -> {
//            try {
//                String contentFormat = StrUtil.isBlank(contentExt) ? this.DINGTALK_MSG_PATTERN : this.DINGTALK_MSG_PATTERN +  contentExt;
//                String content = String.format(contentFormat, this.environment, hostName, reason, num, serverPath, num, num);
//                log.error("发送钉钉消息，content:{}", content);
//                dingTalkSendUtils.sendActioncardMsgToDingRobot(content,"场景计算失败");
//            } catch (ApiException | UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException apiException) {
//                log.error("发送钉钉消息失败", apiException);
//            }
//        });
//    }

//    @Override
//    public Long calUseSpace(Map<String, String> uploadFile) {
//        File spaceFile = null;
//        long space = 0L;
//        for (String key : uploadFile.keySet()) {
//            spaceFile = new File(key);
//            if(spaceFile.exists()){
//                space += spaceFile.length();
//            }
//        }
//        return space;
//    }

    @Override
    public void uploadLogFile(String num, String dataSource) {
        String dataPath = String.format(UploadFilePath.DATA_VIEW_PATH, num);
        String buildLogPath = String.format(UploadFilePath.BUILD_LOG_PATH, num);

        //todo 待删除old_path
        uploadToOssUtil.upload(
            ConstantFilePath.SCENE_PATH + "data/data" + num + File.separator + "status.json",
            "data/data" + num + File.separator + "status.json");

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

        uploadToOssUtil.upload(dataSource + File.separator + "console.log",
            buildLogPath + "console.log");

    }

//    @Override
//    public JSONObject getVideosJson(String path, Integer videoVersion, String projectNum, int cameraType) throws Exception {
//        //读取videos_hdr_param.json, 保存点位视频的value
//        Map<String, Object> 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);
//            if(StorageType.OSS.code().equals(ossType)){
//                videosJson.put("upPath", prefixAli + "data/data" + projectNum + "/Up.xml");
//            }
//            if(StorageType.AWS.code().equals(ossType)){
//                videosJson.put("upPath", ConstantUrl.PREFIX_AWS + "data/data" + projectNum + "/Up.xml");
//            }
//            if(cameraType == 13){
//                //转台相机
//                videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
//            }
//        }else {
//            videosJson.put("version", 1);
//            if("oss".equals(ossType)){
//                videosJson.put("upPath", prefixAli + "data/data" + projectNum + "/Up2.xml");
//            }
//            if("aws".equals(ossType)){
//                videosJson.put("upPath", ConstantUrl.PREFIX_AWS + "data/data" + projectNum + "/Up2.xml");
//            }
//
//            if(cameraType == 13){
//                //转台相机
//                videosJson.put("upPath", videosJson.getString("upPath").replace(".xml", ".txt"));
//            }
//        }
//
//        if(cameraType == 5 || cameraType == 6){
//            videosJson.put("version", 1);
//            if("oss".equals(ossType)){
//                videosJson.put("upPath", prefixAli + "data/data" + projectNum + "/stitch_params.txt");
//            }
//            if("aws".equals(ossType)){
//                videosJson.put("upPath", ConstantUrl.PREFIX_AWS + "data/data" + projectNum + "/stitch_params.txt");
//            }
//        }
//
//        return videosJson;
//    }

//    @Override
//    public String writeSceneJson(String num, JSONObject videosJson, SceneEditInfo sceneEditInfo,
//        SceneEditControls sceneEditControls, ScenePlus scenePlus, ScenePlusExt scenePlusExt, boolean arrearCap)  throws Exception{
//        String sceneJsonPath = String.format(ConstantFilePath.SCENE_PATH_FORMAT, num);
//        String strsceneInfos = FileUtils.readFile(sceneJsonPath);
//        SceneJsonBean sceneJson = null;
//        if(strsceneInfos!=null){
//            sceneJson = JSON.parseObject(strsceneInfos, SceneJsonBean.class);
//        }else{
//            sceneJson = BeanUtil.copyProperties(sceneEditInfo, SceneJsonBean.class);
//            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.setVideos(videosJson);
//        }
//        sceneJson.setVideos(videosJson);
//
//        if(arrearCap) {
//            sceneJson.setPayStatus(PayStatus.NO_CAPACITY.code());
//        }
//
//        String sceneJsonStr = JSON.toJSONString(sceneJson);
//        FileUtils.writeFile(sceneJsonPath, sceneJsonStr);
//        return sceneJsonStr;
//    }
}
