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.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: 经验发放消费者
 * @author: lox
 * @date: 2019/2/22 14:15
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Component
@Slf4j
public class SendExperienceConsumer {

    private static Gson gson = new Gson();

    @Autowired
    @Qualifier("sendExperienceHandleServiceImpl")
    private SynchronizedScoreAndExpService synchronizedScoreAndExpService;

    @Autowired
    private EmailAlertService emailAlertService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QueueMetadata.SendExperience.EXPERIENCE_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = QueueMetadata.EXCHANGE_NAME, type = ExchangeTypes.TOPIC, durable = "true"), key = QueueMetadata.SendExperience.EXPERIENCE_QUEUE_NAME_ROUTING_KEY),
            containerFactory = "rabbitListenerContainerFactory", admin = "rabbitAdmin")
    @RabbitHandler
    public void message(Message message) {
        Long startTime = System.currentTimeMillis();
        String traceId = UUIDUtil.getUUID();
        //ThirdPartyLog.infoConvertJson(traceId, AppContextAware.getAppName(), startTime, System.currentTimeMillis(), "SendExperienceConsumer", 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.SendExperienceError.getDescription(), orderBody == null ? JSON.toJSONString(message) : JSON.toJSONString(orderBody));
        }


    }

}
