package com.fdkanfang.web.mq.listener;

import cn.hutool.core.io.FileUtil;
import com.fdkanfang.common.constant.MsgCode;
import com.fdkanfang.common.enums.ResultCodeEnum;
import com.fdkanfang.common.exception.BaseRuntimeException;
import com.fdkanfang.common.exception.CommonBaseException;
import com.fdkanfang.common.util.AliyunOssUtil;
import com.fdkanfang.common.util.CreateObjUtil;
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.hibernate.boot.spi.InFlightMetadataCollector;
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 org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;

/**
 * Created by owen on 2020/3/16 0016 18:17
 *
 * 垂直校验消息监听
 */
@Log4j2
@Component
@RabbitListener(queues = RabbitConfig.VERTICAL_QUEUE) // 指定监听队列
public class VerticalListener {

    @Autowired
    private HouseService2 houseService2;

    /**
     * order结果监听
     */
    @RabbitHandler
//    @Transactional(rollbackFor = Exception.class)
    public void getMessage(HashMap<Object, Object> mqMap){
        log.info("===================收到MQ消息,开始执行垂直校验===================== ");
        Long houseId = (Long)mqMap.get("id");
        String basePath = (String)mqMap.get("basePath");

        HashMap<String, String>  ossImageHigh = (HashMap<String, String>)mqMap.get("ossImageHigh");
        HashMap<String, String>  ossImageLow = (HashMap<String, String>)mqMap.get("ossImageLow");

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

        long start = System.currentTimeMillis();

        String filePath = basePath+house.getSceneCode();
        try {
            // 后面跟目录路径就可以了
            String cmd  = "bash /home/ubuntu/HorizonNet/run.sh " + filePath ;
            log.info("算法linux指令为:{}", cmd);
            // 调用算法
            CreateObjUtil.callshell(cmd);

            long end = System.currentTimeMillis();
            log.info("调用算法部垂直校验脚本执行耗时: {} s", (end-start)/1000);

            /**
             * 假如算法少于2秒就结束，证明算法发生了错误；
             */
            if (end < 2) {
                log.error("rsaVertical 计算异常");
                throw new BaseRuntimeException(MsgCode.e_RSA_VERTICAL_6000, MsgCode.msg_RSA_VERTICAL_6000);
            }

            // 模型上传oss
            AliyunOssUtil.uploadMulFiles(ossImageHigh);
            AliyunOssUtil.uploadMulFiles(ossImageLow);
            log.info("oss上传完成");

            // 保存信息到db
            // 读取算法生成的scene.json内容到数据库
            String scenePath = filePath + "/scene.json";
            String sceneJson = FileUtil.readString(scenePath, "utf-8");

            house.setSceneJson(sceneJson);

            // 1：成功
            house.setStatus(1);
            log.info("t houseId: {}", house.toString());

        } catch (Exception e) {
            log.error("error VerticalListener 转换异常:{}" , e);
            // 2：失败
            house.setStatus(2);
            e.printStackTrace();
        } finally {
            house.setUpdateTime(new Date());
            int update = houseService2.update(house);
            if(update == 1){
                log.info("垂直校验后，更新房源[{}]状态[{}]成功" , house.getId() , house.getStatus());
            }else{
                log.info("垂直校验后，更新房源[{}]状态[{}]失败" , house.getId() , house.getStatus());
                throw new CommonBaseException(ResultCodeEnum.D101 , "更新房源状态失败");
            }

        }
        log.info("===================处理完MQ消息,房源[{}]的垂直校验完成===================== ", house.getId());
    }



}
