package com.fdkankan.scene.listener;

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.BuildStatus;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.mq.message.BuildSceneResultMqMessage;
import com.fdkankan.platform.api.feign.PlatformGoodsClient;
import com.fdkankan.platform.api.feign.PlatformUserClient;
import com.fdkankan.platform.api.vo.CameraDetail;
import com.fdkankan.platform.api.vo.UserIncrement;
import com.fdkankan.scene.entity.SceneFileBuild;
import com.fdkankan.scene.entity.ScenePro;
import com.fdkankan.scene.entity.SceneProExt;
import com.fdkankan.scene.service.ISceneFileBuildService;
import com.fdkankan.scene.service.ISceneProExtService;
import com.fdkankan.scene.service.ISceneProService;
import com.fdkankan.scene.service.ISceneService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "${rocketmq.consumer.group}",
        topic = "${rocketmq.build-scene-result.topicName.topic-modeling-a}",
        messageModel = MessageModel.CLUSTERING)
public class BuildSceneResultMQListener implements RocketMQListener<String> {

    @Value("${rocketmq.consumer.group}")
    private String consumerGroup;

    @Value("${rocketmq.build-scene-result.topicName.topic-modeling-a}")
    private String buildSceneResultTopic;

    @Autowired
    ISceneService sceneService;
    @Autowired
    ISceneFileBuildService sceneFileBuildService;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    ISceneProExtService sceneProExtService;
    @Autowired
    PlatformGoodsClient platformGoodsClient;
    @Autowired
    PlatformUserClient platformUserClient;


    @Override
    public void onMessage(String message) {

        BuildSceneResultMqMessage resultMqMessage = JSONObject.parseObject(message, BuildSceneResultMqMessage.class);
        log.info("开始处理消息，消费者组：{}，主题名：{}， 消息内容：{}", consumerGroup, buildSceneResultTopic, message);
        process(resultMqMessage);
    }

    private void process(BuildSceneResultMqMessage message){
        try {
            int cameraType = Integer.parseInt(message.getCameraType());
            String sceneCode = message.getSceneCode();
            String fileId = message.getFileId();
            Long space = message.getSpace();
            Integer payStatus = message.getPayStatus();
            String videosJson = message.getVideosJson();
            Long computeTime = message.getComputeTime();
            Boolean buildSuccess = message.getBuildSuccess();
            Integer sceneStatus = message.getSceneStatus();
            if(!buildSuccess){//建模失败，修改状态为失败状态
                log.error("建模失败，修改状态为失败状态");
                sceneService.updateStatus(sceneCode, -1);
                SceneFileBuild sceneFileBuild = sceneFileBuildService.findByFileId(fileId);
                sceneFileBuild.setBuildStatus(BuildStatus.fail.code());
                sceneFileBuildService.updateById(sceneFileBuild);
                return;
            }

            //建模成功
            log.info("cameraType:{}",cameraType);
            if(cameraType < 3){
                sceneService.updateTime(sceneCode, space, payStatus);
            }else{
                sceneProService.updateTime(sceneCode, space, payStatus, videosJson, computeTime);
                SceneFileBuild sceneFileBuild = sceneFileBuildService.findByFileId(fileId);
                if(sceneFileBuild != null){
                    sceneFileBuild.setBuildStatus(BuildStatus.success.code());
                    sceneFileBuildService.updateById(sceneFileBuild);
                }
                //更改相机容量
                ScenePro scenePro = sceneProService.findBySceneNum(sceneCode);
                if(Objects.nonNull(scenePro)){
                    SceneProExt sceneProExt = sceneProExtService.findBySceneProId(scenePro.getId());
                    ResultData<CameraDetail> resultData = platformGoodsClient.updateCameraDetailByCameraIdAndSpace(scenePro.getCameraId(), sceneProExt.getSpace());
                    if(resultData.getCode() != 200){
                        log.error("调用platform服务updateCameraDetailByCameraIdAndSpace失败，参数{},{}" ,scenePro.getCameraId(), sceneProExt.getSpace());
                        return ;
                    }
                    CameraDetail cameraDetail = JSONObject.parseObject(JSONObject.toJSONString(resultData.getData()), CameraDetail.class);

                    ResultData<UserIncrement> resultData1 = platformUserClient.getUserIncrementByCameraId(scenePro.getCameraId());
                    if(resultData1.getCode() != 200){
                        log.error("调用platform服务getUserIncrementByCameraId失败，参数{}" ,scenePro.getCameraId());
                        return;
                    }
                    if( resultData1.getData() == null || resultData1.getData().getIsExpired() ==1) {
                        // 新上传的场景，如果总容量小于使用容量，则该大场景保留在临时存储空间30天
                        if (cameraDetail.getTotalSpace().compareTo(cameraDetail.getUsedSpace()) == -1){
                            List<Long> ids = new ArrayList<>();
                            ids.add(scenePro.getId());
                            sceneProService.tempScenes(ids);
                        }
                    }
                }

            }
        }catch ( Exception e){
            log.error("处理消息出错：{}",e);
        }
    }

}
