package com.fdkankan.ucenter.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.util.JwtUtil;
import com.fdkankan.fyun.face.FYunFileServiceInterface;
import com.fdkankan.ucenter.common.BaseController;
import com.fdkankan.ucenter.common.SceneSourceUtil;
import com.fdkankan.ucenter.common.constants.ConstantFilePath;
import com.fdkankan.common.constant.SceneConstant;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.ucenter.common.PageInfo;
import com.fdkankan.common.util.FileUtils;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.ucenter.common.OssPath;
import com.fdkankan.ucenter.constant.CameraConstant;
import com.fdkankan.ucenter.constant.CameraTypelEnum;
import com.fdkankan.ucenter.constant.LoginConstant;
import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.httpClient.service.LaserService;
import com.fdkankan.ucenter.mapper.IScenePlusMapper;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.vo.request.AppSceneParam;
import com.fdkankan.ucenter.vo.response.AppSceneVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.language.Nysiis;
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.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AppSceneService extends BaseController {
    @Autowired
    IUserService userService;
    @Autowired
    ICameraService cameraService;
    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    IScenePlusService scenePlusService;
    @Autowired
    IScenePlusExtService scenePlusExtService;
    @Autowired
    ISceneEditInfoService sceneEditInfoService;
    @Autowired
    ISceneProEditService sceneProEditService;
    @Autowired
    IUserIncrementService userIncrementService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISceneCooperationService sceneCooperationService;
    @Autowired
    LaserService laserService;
    @Autowired
    ISceneCopyLogService sceneCopyLogService;

    @Autowired
    IScenePlusMapper scenePlusMapper;
    @Autowired
    IExceedSpaceSceneService exceedSpaceSceneService;
    @Autowired
    FYunFileServiceInterface fYunFileServiceInterface;


    @Value("${fyun.host}")
    private String ossHost;

    public PageInfo pageList(AppSceneParam param) {
        if(StringUtils.isEmpty(param.getAppUserName()) && StringUtils.isEmpty(param.getPhoneNum())){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        if(!StringUtils.isEmpty(param.getAppUserName())){
            Camera camera = cameraService.getByChildName(param.getAppUserName());
            if(camera == null){
                throw new BusinessException(LoginConstant.FAILURE_CODE_3014, LoginConstant.FAILURE_MSG_3014);
            }
            CameraDetail cameraDetail = cameraDetailService.getByCameraId(camera.getId());
            if(cameraDetail == null){
                throw new BusinessException(LoginConstant.FAILURE_CODE_3014, LoginConstant.FAILURE_MSG_3014);
            }
            param.setSnCode(camera.getSnCode());
            param.setCameraId(camera.getId());
        }

        List<String> cooperationNumList = new ArrayList<>();
        if(StringUtils.isNotBlank(param.getPhoneNum())){
            User user = userService.getByUserName(param.getPhoneNum());
            if(user == null){
                throw new BusinessException(LoginConstant.FAILURE_CODE_3015, LoginConstant.FAILURE_MSG_3015);
            }
            cooperationNumList = sceneCooperationService.getNumByUserIds(Arrays.asList(user.getId()));
            if(cooperationNumList.size() >0){
                param.setCooperationNumList(cooperationNumList );
            }
            param.setUserId(user.getId());
        }
        //云端场景不展示复制场景
        Set<String> copyNumSet = sceneCopyLogService.getCopyNumSet();
        param.setCopyNumSet(copyNumSet);

        CameraTypelEnum cameraTypelEnum = CameraTypelEnum.getByCameraType(param.getCameraType());
        if(cameraTypelEnum == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6028, CameraConstant.FAILURE_MSG_6028);
        }

        param.setIsLaser(cameraTypelEnum.getLaser());
        
        Page<AppSceneVo> page =  scenePlusMapper.pageList(new Page<>(param.getPageNum(),param.getPageSize()),param);
        List<String> numList = page.getRecords().stream().map(AppSceneVo::getNum).collect(Collectors.toList());




        HashMap<String, JSONObject> ssSceneMap = new HashMap<>();
        if(cameraTypelEnum.getLaser() ){  //深时
            ssSceneMap = laserService.list(numList,cameraTypelEnum.getSceneSource().get(0));
        }

//        Set<Long> cameraIdSet = page.getRecords().stream().map(AppSceneVo::getCameraId).collect(Collectors.toSet());
//        List<Long> cameraIds =  new ArrayList<>(cameraIdSet);
//        HashMap<Long, Camera> cameraHashMap = cameraService.getByIds(cameraIds);
//        HashMap<Long, CameraDetail> detailHashMap = cameraDetailService.getByCameraIds(cameraIds);
        //账号密码登录 sceneSourceType 取值 1用户场景，2协作场景
        //相机登录     sceneSourceType 取值皆为0

        for (AppSceneVo record : page.getRecords()) {
            if(cameraTypelEnum.getLaser()){  //深时
                JSONObject ssObj = ssSceneMap.get(record.getNum());
                if(ssObj!=null){
                    record.setSceneName(ssObj.getString("title"));
                    record.setThumb(ssObj.getString("thumb"));
                    record.setWebSite(ssObj.getString("webSite"));
                    record.setViewCount(ssObj.getInteger("viewCount"));
                }else{
                    record.setStatus(-1);
                    record.setWebSite(null);
                }
            }
            //全景看看场景重置webSite panorama/show.html?id=
            if(record.getLocation() != null && record.getLocation() == 7){
                String newWebSite = record.getWebSite().replaceAll("smg.html\\?m=","panorama/show.html?id=");
                record.setWebSite(newWebSite);
            }

            if (record.getStatus() == -1) {
                record.setStatus(0);
            } else if (record.getStatus() == 500) {
                record.setStatus(-1);
            }
            //虚拟场景
            if(record.getCameraId() == null && param.getUserId() != null){
                record.setSceneSourceType(record.getUserId().equals(param.getUserId()) ? 1 :2);
                continue;
            }
            //相机场景
            if(param.getCameraId() !=null && record.getCameraId().equals(param.getCameraId())){
                record.setSceneSourceType(0);
                continue;
            }
            //用户场景
            if(param.getUserId() != null && record.getUserId() != null){
                record.setSceneSourceType(record.getUserId().equals(param.getUserId()) ? 1 :2);
            }
        }
        return PageInfo.PageInfo(page);
    }

    public HashMap<String, Object> getSceneStatusByUnicode(String appUserName, String appPassword, String unicode) {
        if(StringUtils.isEmpty(appUserName) || StringUtils.isEmpty(appPassword) || StringUtils.isEmpty(unicode)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        Camera camera = cameraService.getBySnCodeAndPassword(appUserName, appPassword);
        if(camera == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3014, LoginConstant.FAILURE_MSG_3014);
        }
        ScenePro scenePro = sceneProService.getByUnicode(unicode);
        ScenePlusExt plusExt = scenePlusExtService.getByUnicode(unicode);
        ScenePlus scenePlus = null;
        if(plusExt !=null){
            scenePlus = scenePlusService.getById(plusExt.getPlusId());
        }
        if(scenePro == null && scenePlus == null){
            ExceedSpaceScene exceedSpaceScene = exceedSpaceSceneService.getByUnicode(unicode);
            if(exceedSpaceScene == null){
                throw new BusinessException(SceneConstant.FAILURE_CODE_5009, SceneConstant.FAILURE_MSG_5009);
            }else {
                String sceneNum = exceedSpaceScene.getNum();
                String sceneCallPath = null ;
                String v3StatusJson = String.format(OssPath.v3_statusPath, sceneNum);
                String v4StatusJson = String.format(OssPath.v4_statusPath, sceneNum);
                if("V3".equals(exceedSpaceScene.getVersion())){
                    sceneCallPath = v3StatusJson;
                }
                if("V4".equals(exceedSpaceScene.getVersion())){
                    sceneCallPath = v4StatusJson;
                }
                if(StringUtils.isBlank(sceneCallPath)){
                    if(fYunFileServiceInterface.fileExist(v3StatusJson)){
                        sceneCallPath = v3StatusJson;
                    }
                    if(fYunFileServiceInterface.fileExist(v4StatusJson)){
                        sceneCallPath = v4StatusJson;
                    }
                }
                if(StringUtils.isBlank(sceneCallPath)){
                    throw new BusinessException(SceneConstant.FAILURE_CODE_5009, SceneConstant.FAILURE_MSG_5009);
                }
                return getReturnMap(-1,null,sceneNum,null,
                        "/mnt/data/"+camera.getSnCode()+"/"+exceedSpaceScene.getFileId()+"/"+exceedSpaceScene.getUnicode(),1,sceneCallPath);
            }
        }
        Integer payStatus = scenePro == null ? scenePlus.getPayStatus() : scenePro.getPayStatus();
        // 当计算时，返回给前端的状态为计算中
        Integer status = scenePro == null ? scenePlus.getSceneStatus() : scenePro.getStatus();
        if(status == -1){
            status = 0;
        }else if(status == 500){
            status = -1;
        }
        String webSite = scenePro == null ? plusExt.getWebSite() : scenePro.getWebSite();
        String sceneNum = scenePro == null ? scenePlus.getNum() : scenePro.getNum();
        String thumb = scenePro == null ? plusExt.getThumb() : scenePro.getThumb();
        String dataSource = scenePro == null ? plusExt.getDataSource() : scenePro.getDataSource();
        String sceneCallPath = scenePro == null ? String.format(OssPath.v4_statusPath,sceneNum) : String.format(OssPath.v3_statusPath,sceneNum);

        return getReturnMap(status,webSite,sceneNum,thumb,dataSource,payStatus,sceneCallPath);
    }

    private HashMap<String,Object> getReturnMap(Integer status,String webSite,String sceneNum,String thumb,String dataSource,Integer payStatus,String sceneCallPath){
        HashMap<String,Object> map = new HashMap<>();
        map.put("status",status == -2 ? 1:status);
        map.put("webSite",webSite);
        map.put("sceneNum",sceneNum);
        map.put("thumb",thumb);
        map.put("dataSource",dataSource);
        map.put("payStatus",payStatus);
        map.put("recStatus","A");
        map.put("sceneCallPath",ossHost+sceneCallPath);
        return map;
    }

    public void getScreencapVoice(String screencapMusic, String originalFileName, String sceneNum) throws Exception {
        if(StringUtils.isEmpty(screencapMusic) || StringUtils.isEmpty(originalFileName) || StringUtils.isEmpty(sceneNum)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001,LoginConstant.FAILURE_MSG_3001);
        }
        ScenePro scenePro = sceneProService.getByNum(sceneNum);
        ScenePlus scenePlus = scenePlusService.getByNum(sceneNum);
        if(scenePro == null && scenePlus == null){
            throw new BusinessException(SceneConstant.FAILURE_CODE_5005,SceneConstant.FAILURE_MSG_5005);
        }
        long time = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put("screencapVoiceSoundsyncFileName", screencapMusic + ".mp3");
        map.put("screencapVoiceSoundsync", originalFileName + "?t=" + time);
        log.info("微信上传的音频路径：" + originalFileName + "?t=" + time);
        map.put("screencapVoiceType", "soundsync");

        SceneProEdit sceneProEdit= null;
        SceneEditInfo editInfo = null;
        if(scenePro !=null){
            sceneProEdit = sceneProEditService.getByProId(scenePro.getId());
            Integer version = sceneProEdit.getVersion() + 1;
            sceneProEdit.setVersion(version);
            sceneProEdit.setScreencapVoiceSoundsync(originalFileName + "?t=" + time);
            sceneProEdit.setScreencapVoiceType("soundsync");
            map.put("version", version);
        }else {
            editInfo = sceneEditInfoService.getByScenePlusId(scenePlus.getId());
            Integer version = editInfo.getVersion() + 1;
            editInfo.setVersion(version);
            //editInfo.setScreencapVoiceSoundsync(originalFileName + "?t=" + time);
            //editInfo.setScreencapVoiceType("soundsync");
            map.put("version", version);
        }
        StringBuilder dataBuffer = new StringBuilder(ConstantFilePath.SCENE_PATH)
                .append("data").append(File.separator)
                .append("data").append(sceneNum);
        FileUtils.writeJsonFile(dataBuffer.append(File.separator).append("scene.json").toString(), map);

        FileUtils.downLoadFromUrl(originalFileName + "?t=" + time, screencapMusic + ".mp3",
                ConstantFilePath.SCENE_PATH+ "voice" + File.separator + "voice" + sceneNum);
        if(sceneProEdit!=null){
            sceneProEditService.updateById(sceneProEdit);
        }
        if(editInfo !=null){
            sceneEditInfoService.updateById(editInfo);
        }

    }

    public void deleteForCameraName(Long cameraId, String sceneNum,Long userId) {
        if( StringUtils.isEmpty(sceneNum)){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001,LoginConstant.FAILURE_MSG_3001);
        }
        ScenePro scenePro = sceneProService.getByNum(sceneNum);
        ScenePlus scenePlus = scenePlusService.getByNum(sceneNum);
        if(scenePro == null && scenePlus == null){
            throw new BusinessException(SceneConstant.FAILURE_CODE_5005, SceneConstant.FAILURE_MSG_5005);
        }
        if(scenePro !=null && scenePro.getStatus() == 0){
            throw new BusinessException(SceneConstant.FAILURE_CODE_5037, SceneConstant.FAILURE_MSG_5037);
        }
        if(scenePlus != null && scenePlus.getSceneStatus() == 0){
            throw new BusinessException(SceneConstant.FAILURE_CODE_5037, SceneConstant.FAILURE_MSG_5037);
        }
        if(cameraId != null && scenePro!=null && !scenePro.getCameraId().equals(cameraId)){
            throw new BusinessException(SceneConstant.FAILURE_CODE_5010, SceneConstant.FAILURE_MSG_5010);
        }
        if(cameraId != null && scenePlus!=null && !scenePlus.getCameraId().equals(cameraId)){
            throw new BusinessException(SceneConstant.FAILURE_CODE_5010, SceneConstant.FAILURE_MSG_5010);
        }
        Integer sceneSource = null;
        List<ScenePro> proList = new ArrayList<>();
        if(scenePro!=null){
            proList.add(scenePro);
            sceneSource = scenePro.getSceneSource();
        }
        List<ScenePlus> plusList = new ArrayList<>();
        if(scenePlus!=null){
            plusList.add(scenePlus);
            sceneSource = scenePlus.getSceneSource();
        }
        sceneProService.deleteByList(proList,plusList,userId, null);

        if(sceneSource != null && (SceneSourceUtil.isLaser(sceneSource))){
            laserService.delete(sceneNum);
        }
    }

}
