package cn.freemud.consumer;

import cn.freemud.amp.EnumEmailAlert;
import cn.freemud.amp.PushOrderConfig;
import cn.freemud.amp.body.OrderBody;
import cn.freemud.amp.constant.QueueMetadata;
import cn.freemud.amp.util.BodyConvertUtil;
import cn.freemud.amqp.MQMessage;
import cn.freemud.order.entity.OrderPushLog;
import cn.freemud.order.mapper.OrderPushLogMapper;
import cn.freemud.resposne.SynchronizationOrderResponse;
import cn.freemud.service.SynchronizedOrderService;
import cn.freemud.util.UUIDUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.service.EmailAlertService;
import org.apache.commons.lang.exception.ExceptionUtils;
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.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 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.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@AutoConfigureAfter(PushOrderConfig.class)
@Component
public class PushOrderConsumer {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier("synchronizedOrderHualalaServiceImpl")
    private SynchronizedOrderService synchronizedOrderService;
    @Autowired
    private OrderPushLogMapper orderPushLogMapper;
    @Autowired
    private EmailAlertService emailAlertService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QueueMetadata.Order.QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = QueueMetadata.EXCHANGE_NAME, type = ExchangeTypes.TOPIC, durable = "true"), key = QueueMetadata.Order.QUEUE_NAME_ROUTING_KEY),
            containerFactory = "rabbitListenerContainerFactory", admin = "rabbitAdmin")
    @RabbitHandler
    public void message(Message message) {
        MQMessage<OrderBody> mqMessage = BodyConvertUtil.orderJsonStringConvertToOrderBody(message);
        OrderBody orderBody = null;
        OrderPushLog orderPushLog = new OrderPushLog();
        String traceId = UUIDUtil.getUUID();
        try {
            orderBody = mqMessage.getBody();
            Date startDate = new Date();

            orderPushLog.setPushDate(startDate);
            orderPushLog.setOrderId(orderBody.getOrderBean().getOid());
            orderPushLog.setPartnerId(orderBody.getOrderBean().getCompanyId());
            orderPushLog.setPlatformStoreId(orderBody.getOrderBean().getShopId());
            orderPushLog.setRequestBody(JSON.toJSONString(orderBody));
            orderPushLog.setTraceId(traceId);
            orderPushLog.setPushDate(startDate);
            SynchronizationOrderResponse synchronizationOrderResponse = synchronizedOrderService.synchronizationOrder(traceId, orderBody,"","","","",1);
            if (!synchronizationOrderResponse.getResult()) {
                orderPushLog.setFailureReasons(synchronizationOrderResponse.getMessage());
                orderPushLogMapper.insert(orderPushLog);
                emailAlertService.sendEmailAlert(EnumEmailAlert.Description.OrderPushError.getDescription(), JSON.toJSONString(orderBody));
            }
        } catch (Exception e) {
            ErrorLog.infoConvertJson(SDKCommonBaseContextWare.getAppName(), traceId, getClass(), "PushOrderConsumer异常", e);
            orderPushLog.setFailureReasons(e.getMessage());
            orderPushLogMapper.insert(orderPushLog);
            emailAlertService.sendEmailAlert(EnumEmailAlert.Description.OrderPushError.getDescription(), e);
            logger.error("PushOrderConsumer body:{} error:{} 发送出错", JSONObject.toJSONString(orderBody), ExceptionUtils.getStackTrace(e));
            return;
        }

    }

}
