package cn.freemud.consumer;

import cn.freemud.amp.EnumEmailAlert;
import cn.freemud.amp.constant.QueueMetadata;
import cn.freemud.amp.util.BodyConvertUtil;
import cn.freemud.amqp.MQMessage;
import cn.freemud.config.AppContextAware;
import cn.freemud.resposne.SynchronizationOrderResponse;
import cn.freemud.service.SynchronizedScoreAndExpService;
import cn.freemud.util.UUIDUtil;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.service.EmailAlertService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;


/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package com.freemud.mail.core
 * @Description: ${TODO}(用一句话描述该文件做什么)
 * @author: aiqi.gong
 * @date: 2019/2/22 14:15
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Component
@Slf4j
public class     SendScoreConsumer {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private EmailAlertService emailAlertService;
    @Autowired
    @Qualifier("sendScoreHandleServiceImpl")
    private SynchronizedScoreAndExpService synchronizedScoreAndExpService;

    private static Gson gson = new Gson();


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QueueMetadata.Score.SCORE_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = QueueMetadata.EXCHANGE_NAME, type = ExchangeTypes.TOPIC, durable = "true"), key = QueueMetadata.Score.SCORE_QUEUE_NAME_ROUTING_KEY),
            containerFactory = "rabbitListenerContainerFactory", admin = "rabbitAdmin")
    @RabbitHandler
    public void message(Message message) {
        Long startTime = System.currentTimeMillis();
        String traceId = UUIDUtil.getUUID();
        //ApiLog.info(AppContextAware.getAppName(), traceId, "SendScoreConsumer", message, "");
        //ThirdPartyLog.infoConvertJson(traceId, AppContextAware.getAppName(), startTime, System.currentTimeMillis(), "SendScoreConsumer", message, "");
        OrderInfoReqs orderBody = null;

        try {
            MQMessage<OrderInfoReqs> mqMessage = BodyConvertUtil.orderJsonStringConvertToOrderInfoReqs(message, traceId);
            orderBody = mqMessage.getBody();
            ThirdPartyLog.infoConvertJson(traceId, AppContextAware.getAppName(), startTime, System.currentTimeMillis(), "SendExperienceConsumer orderbody", message, "");
            if (null == orderBody) {
                return;
            }
            //非saas订单不推送积分
            if(ObjectUtils.notEqual(OrderClientType.SAAS.getIndex(),orderBody.getOrderClient())) {
                return;
            }
            SynchronizationOrderResponse synchronizationOrderResponse = synchronizedScoreAndExpService.synchronizationOrder(traceId, orderBody);
            if (!synchronizationOrderResponse.getResult()) {
                //ApiLog.info(AppContextAware.getAppName(), traceId, "积分发送失败", JSON.toJSONString(orderBody));
                ThirdPartyLog.infoConvertJson(traceId, SDKCommonBaseContextWare.getAppName(), startTime, System.currentTimeMillis(), "积分发送失败", orderBody, synchronizationOrderResponse);
            }
        } catch (Exception e) {
            //ApiLog.info(AppContextAware.getAppName(), traceId, "积分-异常", JSON.toJSONString(orderBody), e);
            ErrorLog.infoConvertJson(SDKCommonBaseContextWare.getAppName(), traceId, getClass(), "积分-异常", e);
            emailAlertService.sendEmailAlert(EnumEmailAlert.Description.SendScoreError.getDescription(), orderBody == null ? JSON.toJSONString(message) : JSON.toJSONString(orderBody));
        }
    }


}
