package com.fdkanfang.web.mq.listener;

import com.fdkanfang.common.constant.MsgCode;
import com.fdkanfang.common.exception.BaseRuntimeException;
import com.fdkanfang.common.util.AliyunOssUtil;
import com.fdkanfang.common.util.ComputerUtil;
import com.fdkanfang.domain.backend.HouseEntity;
import com.fdkanfang.service.backend.HouseService2;
import com.fdkanfang.web.mq.config.RabbitConfig;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by owen on 2020/3/16 0016 18:17
 *
 * 生成模型消息监听
 */
@Log4j2
@Component
@RabbitListener(queues = RabbitConfig.PANO_QUEUE) // 指定监听队列
public class PanoListener {

    @Autowired
    private HouseService2 houseService2;

    /**
     * 结果监听
     */
    @RabbitHandler
    public void getMessage(HashMap<Object, Object> mqMap)  {
        log.info("run PanoListener ");

        LocalDateTime starTime = LocalDateTime.now();

        Long houseId = (Long)mqMap.get("id");
        String basePath = (String)mqMap.get("basePath");
        String splitType = (String)mqMap.get("splitType");
        String skyboxType = (String)mqMap.get("skyboxType");
        String dataDescribe = (String)mqMap.get("dataDescribe");

        HouseEntity house = houseService2.findById(houseId);
        if (house == null) {
            throw new BaseRuntimeException(MsgCode.e_COMMON_3002, MsgCode.msg_COMMON_3002);
        }

        String sceneCode = house.getSceneCode();

        try {


            //计算模型并返回需要上传oss的文件集合
            Map<String, String> map = ComputerUtil.computer(sceneCode, sceneCode, basePath);

            // 模型上传oss
            AliyunOssUtil.uploadMulFiles(map);
            log.info("oss upload success");

            // 3：rsaPano 成功
            house.setStatus(4);

        } catch (Exception e) {
            // 4：rsaPano失败
            house.setStatus(5);
            e.printStackTrace();
        } finally {
            house.setUpdateTime(new Date());

            houseService2.update(house);
            log.info("update db success");

        }
        LocalDateTime endTime = LocalDateTime.now();

        Duration.between(starTime, endTime);
        log.info("total time: {} s", Duration.between(starTime, endTime).getSeconds());
        log.info("end PanoListener houseId:{}", house.getId());
    }

    @RabbitHandler
    public void getMessage(String msg)  {
        log.info("run testPanoListener ");


        log.info("end testPanoListener msg: {}", msg);
    }



}
