package com.fdkankan.ucenter.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fdkankan.common.constant.SceneVersionType;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.common.util.SnowflakeIdGenerator;
import com.fdkankan.fyun.face.FYunFileServiceInterface;
import com.fdkankan.ucenter.common.constants.ResultCodeMsg;
import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.util.SceneResourcePath;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SceneCommonService {

    @Autowired
    FYunFileServiceInterface fYunFileServiceInterface;
    @Autowired
    IScene3dNumService scene3dNumService;

    public String getNewNum(String oldNum ){
        String newNum = scene3dNumService.generateSceneNum(1);
        if(oldNum.contains("-")){
            String pre = oldNum.split("-")[0];
            if(!"t".equals(pre) && !"jp".equals(pre)){
                return pre +"-"+ newNum;
            }
        }
        return newNum;
    }

    /**
     * 生成新的dataSouce
     */
    public String getNewDataSource(String oldDataSource){

        String newDataSource = null;
        if(StringUtils.isBlank(oldDataSource)){
            throw new BusinessException(ResultCodeMsg.FAILURE_CODE_400006, ResultCodeMsg.FAILURE_MSG_400006);
        }
        if(!oldDataSource.contains("/")){
            throw new BusinessException(ResultCodeMsg.FAILURE_CODE_400006, ResultCodeMsg.FAILURE_MSG_400006);
        }

        String time = com.fdkankan.common.util.DateUtil.date2String(new Date(), com.fdkankan.common.util.DateUtil.YYYYMMDDHHMMSSSSS_DATA_FORMAT);
        String[] split = oldDataSource.split("/");
        if(split.length == 6 ){
            String oldFileId = split[4];
            Long fileId = new SnowflakeIdGenerator(1,1).nextId();
            newDataSource = oldDataSource.replace(oldFileId,fileId.toString());

            String snCodeTime = split[5];
            if(!snCodeTime.contains("_") || snCodeTime.split("_").length <= 1){
                throw new BusinessException(ResultCodeMsg.FAILURE_CODE_400006, ResultCodeMsg.FAILURE_MSG_400006);
            }
            newDataSource = newDataSource.replace(snCodeTime.split("_")[1],time);
            //this.copyFdage(oldDataSource,newDataSource,time);
        }
        if(newDataSource == null){
            throw new BusinessException(ResultCodeMsg.FAILURE_CODE_400006, ResultCodeMsg.FAILURE_MSG_400006);
        }
        return newDataSource;
    }

  public  void createNewQrCode(String sceneVersion,String logoPath ,String newNum, String webSite){
      String localLogoPath = null;
      try {
          if(StringUtils.isNotBlank(logoPath)){
              if(sceneVersion.equals(SceneVersionType.V3.code())){
                  localLogoPath =SceneResourcePath.nasBasePath + logoPath;
              }else{
                  localLogoPath = SceneResourcePath.qrCodeBasePath + newNum +"/logo/logo.png";
                  fYunFileServiceInterface.downloadFile(logoPath,localLogoPath);
              }
          }
          String outPathZh = SceneResourcePath.qrCodeBasePath + newNum + ".png";
          String outPathEn = SceneResourcePath.qrCodeBasePath + newNum + "_en.png";
          QrConfig qrConfig = QrConfig.create();
          qrConfig.setWidth(1024);
          qrConfig.setHeight(1024);
          if(!ObjectUtils.isEmpty(localLogoPath)){
              qrConfig.setImg(localLogoPath);
          }
          QrCodeUtil.generate(webSite, qrConfig, FileUtil.file(outPathZh));
          QrCodeUtil.generate(webSite + "&lang=en", qrConfig, FileUtil.file(outPathEn));

          fYunFileServiceInterface.uploadFile(outPathZh, String.format(SceneResourcePath.DOWNLOADS_QRCODE, newNum) + newNum + ".png");
          fYunFileServiceInterface.uploadFile(outPathEn, String.format(SceneResourcePath.DOWNLOADS_QRCODE, newNum) + newNum + "_en.png");
        }catch (Exception e){
            log.info("copy-scene-error:{},newNum:{},error:{}",newNum,e);
        }

    }


    public void updateNasSceneJson(String targetPath, String oldNum, String newNum,String newSceneName,String sceneVersion,String fileName) {
        String fileContent = null;
        if("v3".equals(sceneVersion)){
            String localPath = SceneResourcePath.nasBasePath + targetPath + "/" + fileName;
            File file = new File(localPath);
            if(!file.exists()){
                log.error("sceneCopy-error--localFileExist:localPath:{},oldNum:{},newNum:{}",localPath,oldNum,newNum);
                return;
            }
            fileContent = FileUtil.readUtf8String(file);
        }
        if("v4".equals(sceneVersion)){
            String ossStatusJsonPath =  targetPath + "/" + fileName;
            if(!fYunFileServiceInterface.fileExist(ossStatusJsonPath)){
                log.error("sceneCopy-error--ossFileExist:targetPath:{},oldNum:{},newNum:{}",ossStatusJsonPath,oldNum,newNum);
                return;
            }
            fileContent = fYunFileServiceInterface.getFileContent(ossStatusJsonPath);
        }

        if(StringUtils.isNotBlank(fileContent)){
            //v3编辑器使用
            String localPath = SceneResourcePath.nasBasePath + targetPath +"/" + fileName;
            File file = new File(localPath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            String newJson = fileContent.replaceAll(oldNum,newNum);
            try {
                if("v3".equals(sceneVersion)){
                    if(fileName.contains("scene.json")){
                        JSONObject jsonObject = JSONObject.parseObject(newJson);
                        jsonObject.put("sceneName",newSceneName);
                        FileUtils.writeFile(localPath ,jsonObject.toJSONString());
                        String sceneJsonPath = String.format(SceneResourcePath.dataPath+"/"+fileName, newNum);
                        fYunFileServiceInterface.uploadFile(localPath, sceneJsonPath);
                    }else {
                        FileUtils.writeFile(localPath ,newJson);
                    }

                }
                if("v4".equals(sceneVersion)){
                    JSONObject jsonObject = JSONObject.parseObject(newJson);
                    jsonObject.put("title",newSceneName);
                    jsonObject.put("dynamicPanel",0);
                    FileUtils.writeFile(localPath, jsonObject.toJSONString());

                    String sceneJsonPath = String.format(SceneResourcePath.DATA_VIEW_PATH+"/" + fileName, newNum);
                    fYunFileServiceInterface.uploadFile(localPath, sceneJsonPath);

                    //修改图片名称
                    String filePath = String.format(SceneResourcePath.USER_VIEW_PATH, newNum) ;
                    List<String> files = fYunFileServiceInterface.listRemoteFiles(filePath);
                    for (String ossFilePath : files) {
                        if(ossFilePath.contains(oldNum)){
                            String oldName = ossFilePath;
                            ossFilePath = ossFilePath.replace(oldNum,newNum);
                            fYunFileServiceInterface.copyFileInBucket(oldName,ossFilePath);
                            fYunFileServiceInterface.deleteFile(oldName);
                        }
                    }
                    String dynamicViewPath = String.format(SceneResourcePath.DYNAMIC_VIEW_PATH, newNum);
                    String dynamicEditPath = String.format(SceneResourcePath.DYNAMIC_EDIT_PATH, newNum);
                    if(fYunFileServiceInterface.fileExist(dynamicViewPath)){
                        fYunFileServiceInterface.deleteFile(dynamicViewPath);
                    }
                    if(fYunFileServiceInterface.fileExist(dynamicEditPath)){
                        fYunFileServiceInterface.deleteFile(dynamicEditPath);
                    }

                }
            }catch (Exception e){
                log.error("writeFile-error:{}",e);
            }

        }

    }

    public void updateOssJson(String targetPath,String oldNum, String newNum,String fileName) {
        String ossStatusJsonPath =  targetPath + "/" + fileName;

        if(!fYunFileServiceInterface.fileExist(ossStatusJsonPath)){
            log.error("sceneCopy-error--ossFileExist:targetPath:{},oldNum:{},newNum:{}",ossStatusJsonPath,oldNum,newNum);
            return;
        }
        String localPath = SceneResourcePath.nasBasePath + ossStatusJsonPath;
        File file = new File(localPath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        String fileContent = fYunFileServiceInterface.getFileContent(ossStatusJsonPath);
        if(StringUtils.isNotBlank(fileContent)){
            String newJson = fileContent.replaceAll(oldNum,newNum);
            try {
                FileUtils.writeFile(localPath, newJson);
                fYunFileServiceInterface.uploadFile(localPath,ossStatusJsonPath);
            }catch (Exception e){
                log.error("writeFile-error:{}",e);
            }
        }

    }

    public void copyFdage(String oldDataSource,String newDataSource,String time){
        String ossOldPath = oldDataSource.replace("/mnt/data","home");
        String ossNewPath = newDataSource.replace("/mnt/data","home");
        fYunFileServiceInterface.copyFileInBucket(ossOldPath,ossNewPath);

        String fileName = "/data.fdage";

        String fileContent = fYunFileServiceInterface.getFileContent(ossNewPath + fileName);
        if(StringUtils.isNotBlank(fileContent)){
            JSONObject jsonObject = JSONObject.parseObject(fileContent);
            jsonObject.put("uuidtime",time);
            FileUtils.writeFile(newDataSource +fileName, jsonObject.toJSONString());
            fYunFileServiceInterface.uploadFile(newDataSource +fileName,ossNewPath +fileName);

        }

    }

    public void delLink(String path) {
        String panPath = path +"/panorama";
        File file = new File(panPath);
        if(file.exists()){
            File[] files = file.listFiles();
            if(files == null || files.length == 0){
                return;
            }
            for (File file1 : files) {
                String linkPath =file1.getPath() + "/capture";
                log.info("delLink--filePath:{}",linkPath);
                org.apache.commons.io.FileUtils.deleteQuietly(new File(linkPath));
            }
        }
    }

    @Autowired
    ISceneProService sceneProService;
    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    ICameraTypeService cameraTypeService;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    IScenePlusExtService scenePlusExtService;

    public void copyResult(String newNum) {
        ScenePro scenePro = sceneProService.getByNum(newNum);
        ScenePlus scenePlus = scenePlusService.getByNum(newNum);
        if(scenePro == null && scenePlus == null){
            log.info("复制失败：{}",newNum);
            return;
        }
        Long cameraId = scenePro == null ? scenePlus.getCameraId() : scenePro.getCameraId();
        Integer location = null;
        Long space = 0L;
        if(scenePlus != null){
            ScenePlusExt plusExt = scenePlusExtService.getByPlusId(scenePlus.getId());
            if(plusExt == null){
                return;
            }
            location = plusExt.getLocation();
            space = plusExt.getSpace();

        }
        if(scenePro != null){
            space = scenePro.getSpace();
        }
        CameraDetail cameraDetail = cameraDetailService.getByCameraId(cameraId);
        CameraType cameraType = cameraTypeService.getByCameraType(cameraDetail.getType());

        Boolean checkSpace = cameraDetailService.checkSpace(cameraDetail,cameraType);
        if(!checkSpace && (location == null || location != 7)){
            sceneProService.lockOrUnLockScenes(new ArrayList<>(), Arrays.asList(newNum),-2,cameraType.getIsLaser(),null);
        }
        cameraDetailService.addUsedSpace(cameraDetail,space);


        if(cameraType.getIsLaser() == 1 && scenePlus != null){
            LambdaUpdateWrapper<ScenePlus> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(ScenePlus::getId,scenePlus.getId());
            wrapper.set(ScenePlus::getSceneStatus,-2);
            scenePlusService.update(wrapper);
        }
        if(cameraType.getIsLaser() == 1 && scenePro != null){
            LambdaUpdateWrapper<ScenePro> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(ScenePro::getId,scenePro.getId());
            wrapper.set(ScenePro::getStatus,-2);
            sceneProService.update(wrapper);
        }

    }
}
