package cn.gtmap.estateplat.config.rabbitmq.service.impl;
/*
 * @author <a href="mailto:chenjia@gtmap.cn">chenjia</a>
 * @version 1.0, 2019-02-22
 * @description 
 */


import cn.gtmap.estateplat.config.core.service.BdcMessageLogService;
import cn.gtmap.estateplat.config.model.BdcMessageLog;
import cn.gtmap.estateplat.config.model.CorrelationData;
import cn.gtmap.estateplat.config.rabbitmq.service.RabbitmqSendMessageService;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.model.exchange.national.QlfQlZxdj;
import cn.gtmap.estateplat.model.server.core.BdcZs;
import cn.gtmap.estateplat.service.config.GxztService;
import cn.gtmap.estateplat.service.config.QlztService;
import cn.gtmap.estateplat.service.config.RedundantFieldService;
import cn.gtmap.estateplat.utils.CalendarUtil;
import cn.gtmap.estateplat.utils.CommonUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gtis.config.AppConfig;
import com.rabbitmq.client.Channel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class RabbitMqConsumerListener implements ChannelAwareMessageListener {
    private Logger logger = LoggerFactory.getLogger(RabbitMqConsumerListener.class);


    @Autowired
    private QlztService qlztService;
    @Autowired
    private GxztService gxztService;
    @Autowired
    private RabbitmqSendMessageService rabbitmqSendMessageService;
    @Autowired
    private RedundantFieldService redundantFieldService;
    @Autowired
    private BdcMessageLogService bdcMessageLogService;

    @Override
    public void onMessage(Message message, Channel channel) {
        String key=message.getMessageProperties().getReceivedRoutingKey();
        try {
            String s = new String(message.getBody(),"UTF-8");
            //将jsonArray字符串转化为JSONArray
            JSONObject jsonObject = JSON.parseObject(s);
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateCxZsZmByCqzh.queue"))&&jsonObject!=null&&jsonObject.containsKey("cqzh")&&StringUtils.isNotBlank(jsonObject.get("cqzh").toString())&&jsonObject.containsKey("bdclx")&&StringUtils.isNotBlank(jsonObject.get("bdclx").toString())){
                logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateCxZsZmByCqzh.queue"));
                qlztService.updateZszmZtByCqzh(jsonObject.get("cqzh").toString(),jsonObject.get("bdclx").toString());
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateCxZsZmByProid.queue"))&&jsonObject!=null&&jsonObject.containsKey("proid")&&StringUtils.isNotBlank(jsonObject.get("proid").toString())){
                logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateCxZsZmByProid.queue"));
                qlztService.updateZszmZtByProid(jsonObject.get("proid").toString());
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateZszmZtByDeleteEnvent.queue"))&&jsonObject!=null&&jsonObject.containsKey("bdcZsList")&&CollectionUtils.isNotEmpty((List<BdcZs>) jsonObject.get("bdcZsList"))){
                logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateZszmZtByDeleteEnvent.queue"));
                qlztService.updateZszmZtByDeleteEnvent(JSON.parseArray(jsonObject.get("bdcZsList").toString(), BdcZs.class));
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateBdcdyZtByBdcdyh.queue"))&&jsonObject!=null&&jsonObject.containsKey("bdclx")&&jsonObject.containsKey("bdcdyhList")){
                logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.updateBdcdyZtByBdcdyh.queue"));
                qlztService.updateBdcdyZtByBdcdyh((List<String>) jsonObject.get("bdcdyhList"),CommonUtil.formatEmptyValue(jsonObject.get("bdclx")));
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.getcqztbywiid.queue.send"))&&jsonObject!=null&&jsonObject.containsKey("wiid")){
                if(StringUtils.equals(AppConfig.getProperty("bdcdj.use.rabbitmq"),"true")){
                    logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.getcqztbywiid.queue.send"));
                    List<Map<String, Object>> cqztList=qlztService.listCqzt(jsonObject.get("wiid").toString());
                    JSONObject returnObject=new JSONObject();
                    returnObject.put("cqztList",cqztList);
                    CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                    correlationData.setMessage(returnObject);
                    correlationData.setRoutingKey(AppConfig.getProperty("bdcdj.rabbitmq.bdc.getcqztbywiid.queue.return"));
                    rabbitmqSendMessageService.sendMsg(CommonUtil.formatEmptyValue(jsonObject.get("wiid")),correlationData.getRoutingKey(),JSON.toJSONString(returnObject),correlationData);
                }
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxyproidsbywiidforback.queue.send"))&&jsonObject!=null&&jsonObject.containsKey("wiid")&&jsonObject.containsKey("isCompara")){
                if(StringUtils.equals(AppConfig.getProperty("bdcdj.use.rabbitmq"),"true")){
                    logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxyproidsbywiidforback.queue.send"));
                    Map map =gxztService.getGxYproidsByWiid(jsonObject.get("wiid").toString(),jsonObject.get("isCompara").toString());
                    Object returnObject = JSON.toJSON(map);
                    CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                    correlationData.setMessage(returnObject);
                    correlationData.setRoutingKey(AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxyproidsbywiidforback.queue.return"));
                    rabbitmqSendMessageService.sendMsg(CommonUtil.formatEmptyValue(jsonObject.get("wiid")),correlationData.getRoutingKey(),JSON.toJSONString(returnObject),correlationData);
                }
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxyproidsbywiidfordelet.queue.send"))&&jsonObject!=null&&jsonObject.containsKey("wiid")&&jsonObject.containsKey("isCompara")){
                if(StringUtils.equals(AppConfig.getProperty("bdcdj.use.rabbitmq"),"true")){
                    logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxyproidsbywiidfordelet.queue.send"));
                    Map map =gxztService.getGxYproidsByWiid(jsonObject.get("wiid").toString(),jsonObject.get("isCompara").toString());
                    Object returnObject = JSON.toJSON(map);
                    CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                    correlationData.setMessage(returnObject);
                    correlationData.setRoutingKey(AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxyproidsbywiidfordelet.queue.return"));
                    rabbitmqSendMessageService.sendMsg(CommonUtil.formatEmptyValue(jsonObject.get("wiid")),correlationData.getRoutingKey(),JSON.toJSONString(returnObject),correlationData);
                }
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxlistbywiid.queue.send"))&&jsonObject!=null&&jsonObject.containsKey("wiid")){
                if(StringUtils.equals(AppConfig.getProperty("bdcdj.use.rabbitmq"),"true")){
                    logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxlistbywiid.queue.send"));
                    List<QlfQlZxdj> qlfQlZxdjList = gxztService.getGxListByWiid(jsonObject.get("wiid").toString());
                    JSONObject returnObject=new JSONObject();
                    returnObject.put("qlfQlZxdjList",qlfQlZxdjList);
                    CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
                    correlationData.setMessage(returnObject);
                    correlationData.setRoutingKey(AppConfig.getProperty("bdcdj.rabbitmq.bdc.getgxlistbywiid.queue.return"));
                    rabbitmqSendMessageService.sendMsg(CommonUtil.formatEmptyValue(jsonObject.get("wiid")),correlationData.getRoutingKey(),JSON.toJSONString(returnObject),correlationData);
                }
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.synchronizationgdfield.queue"))&&jsonObject!=null&&jsonObject.containsKey("proid")){
                logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.synchronizationgdfield.queue"));
                redundantFieldService.synchronizationGdField(jsonObject.get("proid").toString());
            }
            if(StringUtils.equals(key, AppConfig.getProperty("bdcdj.rabbitmq.bdc.synchronizationbdcfield.queue"))&&jsonObject!=null&&jsonObject.containsKey("proid")){
                logger.info("***"+AppConfig.getProperty("bdcdj.rabbitmq.bdc.synchronizationbdcfield.queue"));
                redundantFieldService.synchronizationBdcField(jsonObject.get("proid").toString());
            }

            logger.info("consumer--:" + message.getMessageProperties() + ":" + new String(message.getBody()));
            if(message.getMessageProperties().getCorrelationId() != null) {
                String correlationId = new String(message.getMessageProperties().getCorrelationId(),"UTF-8");
                BdcMessageLog bdcMessageLog = bdcMessageLogService.getBdcMessageLogById(correlationId);
                Date curHMSDate = CalendarUtil.getCurHMSDate();
                if(bdcMessageLog != null){
                    bdcMessageLog.setXfzt(Constants.MESSAGE_XFZT_YXF);
                    bdcMessageLog.setGxsj(curHMSDate);
                    bdcMessageLogService.saveOrUpdateBdcMessageLog(bdcMessageLog);
                    logger.info("update message send status ==="+ JSON.toJSONString(bdcMessageLog));
                }
            }
            basicACK(message, channel); //正常消费掉后通知mq服务器移除此条mq
        } catch (Exception e) {
            basicNACK(message, channel); //处理异常，mq重回队列
            logger.error("context", e);
        }
    }

    //正常消费掉后通知mq服务器移除此条mq
    private void basicACK(Message message, Channel channel) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            logger.error("通知服务器移除mq时异常，异常信息：" + e);
        }
    }

    //处理异常，mq重回队列
    private void basicNACK(Message message, Channel channel) {
        try {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        } catch (IOException e) {
            logger.error("mq重新进入服务器时出现异常，异常信息：" + e);
        }
    }
}
