package com.fdkanfang.common.util;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fdkanfang.common.constant.ConstantFileName;
import com.fdkanfang.common.constant.ConstantFilePath;
import com.fdkanfang.common.constant.MsgCode;
import com.fdkanfang.common.exception.BaseRuntimeException;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成场景和计算场景
 * Created by Hb_zzZ on 2019/5/8.
 */
@Slf4j
public class ComputerUtil {

    /**
     * @param unicode    创建文件目录码（目前是用场景吗）
     * @param projectNum 场景码
     * @param panoRootPath       算法生成文件路径
     * @return
     * @throws Exception
     */
    public static Map<String, String> computer(String unicode, String projectNum, String panoRootPath) throws Exception {
        // path: /data/kanfang/10002/pano
        log.info("建模收到的文件路径为:{}", panoRootPath);
        Map<String, String> map = new HashMap<String, String>();

        // 生成模型oss存放路径
        //TODO:这里需要加斜杆，不然黏连在一起了
//        String ossPanoPath = ConstantFilePath.OSS_IMAGE_PATH  + "/" + projectNum + "/";
        String ossPanoPath = ConstantFilePath.OSS_IMAGE_PATH + projectNum + "/";

        log.info(">>>>>>>>开始建模:{}<<<<<<<<", projectNum);
        //构建算法isModel去掉，因此改成空字符串
        CreateObjUtil.build3dModel(panoRootPath, "");
        log.info("建模完成转换数据：" + projectNum);

        boolean vision2 = false;
        //读取upload文件，检验需要上传的文件是否存在
        String uploadJsonPath = panoRootPath + File.separator + "results" + File.separator + "upload.json";
        boolean exist = FileUtil.exist(uploadJsonPath);
        if (!exist) {
            log.error("模型算法生成的upload.json不存在");
            throw new BaseRuntimeException(MsgCode.e_COMMON_3100, "模型算法生成的upload.json不存在");
        }
        String uploadData = FileUtils.readFile(uploadJsonPath);
        JSONObject uploadJson = null;
        JSONArray uploadFileArray = null;
        if (uploadData != null) {
            uploadJson = JSONObject.parseObject(uploadData);
            uploadFileArray = uploadJson.getJSONArray("upload");
        }
        if (uploadFileArray == null) {
            log.error("模型算法生成的upload.json数据出错");
            throw new BaseRuntimeException(MsgCode.e_COMMON_3100, "模型算法生成的upload.json数据出错");
        }
        JSONObject fileJson = null;
        String fileName = "";
        for (int i = 0, len = uploadFileArray.size(); i < len; i++) {
            fileJson = uploadFileArray.getJSONObject(i);
            fileName = fileJson.getString("file");
            //文件不存在抛出异常
            String filePath = panoRootPath + File.separator + "results" + File.separator + fileName;
            if (!FileUtil.exist(filePath)) {
                log.error("文件不存在: " + filePath);
                throw new BaseRuntimeException(MsgCode.e_COMMON_3100, "文件不存在: " + filePath);
            }

            //判断是否有vision2.txt
            if ("vision2.txt".equals(fileName)) {
                vision2 = true;
            }


            //tex文件夹
            if (fileJson.getIntValue("clazz") == 2 && !fileJson.containsKey("pack-file")) {

                // param1: 文件地址， param2：oss upload 地址
                map.put(filePath, ossPanoPath + ConstantFileName.modelUUID + "_50k_texture_jpg_high1/" + fileName.replace("tex/", ""));
            }

            //high文件夹
            if (fileJson.getIntValue("clazz") == 3) {
                map.put(filePath, ossPanoPath + "pan/high/" + fileName.replace("high/", ""));
            }
            //low文件夹
            if (fileJson.getIntValue("clazz") == 4) {
                map.put(filePath, ossPanoPath + "pan/low/" + fileName.replace("low/", ""));
            }

            //2k/4k照片目录
            if (fileJson.getIntValue("clazz") == 5) {
                map.put(filePath, ossPanoPath +  fileName);
            }
        }

        CreateObjUtil.convertTxtToDam(panoRootPath + File.separator + "results" + File.separator + "tex" + File.separator + "modeldata.txt", panoRootPath + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam");
        // 服务器地址
        // path:/data/kanfang/房源编号/pano
        CreateObjUtil.convertDamToLzma(panoRootPath + "/results/");
        CreateObjUtil.convertTxtToDam(panoRootPath + File.separator + "results" + File.separator + "tex" + File.separator + "modeldata.txt", panoRootPath + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam");
        //8目相机有两个vision.txt因此第二个叫vision2.txt
        if (vision2) {
            CreateObjUtil.convertTxtToVisionmodeldata(panoRootPath + File.separator + "results" + File.separator + "vision.txt", panoRootPath + File.separator + "results" + File.separator + "vision.modeldata");
            CreateObjUtil.convertTxtToVisionmodeldata(panoRootPath + File.separator + "results" + File.separator + "vision2.txt", panoRootPath + File.separator + "results" + File.separator + "vision2.modeldata");
            map.put(panoRootPath + File.separator + "results" + File.separator + "vision2.modeldata", "images/images" + projectNum + "/" + "vision2.modeldata");
        } else {
            // 将前端上传的vision.txt转vision.modeldata
            CreateObjUtil.convertTxtToVisionmodeldata(panoRootPath + "/extras/vision.txt", panoRootPath + "/results/vision.modeldata");
            log.info("vision.modeldata创建完成");
        }
        log.info("场景码[{}]的数据转换完成" + projectNum);

        File file = new File(panoRootPath + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam.lzma");
        while (!file.exists()) {
            Thread.sleep(60000);
        }


        // 文件上传oss
        map.put(panoRootPath + File.separator + "results" + File.separator + "vision.modeldata", ossPanoPath + "vision.modeldata");
        map.put(panoRootPath + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam.lzma", ossPanoPath + ConstantFileName.modelUUID + "_50k.dam.lzma");
        map.put(panoRootPath + File.separator + "results" + File.separator + ConstantFileName.modelUUID + "_50k.dam", ossPanoPath + ConstantFileName.modelUUID + "_50k.dam");

        log.info("场景[{}]准备上传文件到oss：" + projectNum);
        return map;
    }

    public static void createJson(String path, String splitType, String skyboxType, String dataDescribe) throws Exception {
        JSONObject dataJson = new JSONObject();
        dataJson.put("split_type", splitType);
        dataJson.put("skybox_type", skyboxType);
        dataJson.put("data_describe", dataDescribe);
        dataJson.put("extras", null);
        FileUtils.writeFile(path + File.separator + "data.json", dataJson.toString());
    }

}
