package cn.freemud.consumer;

import cn.freemud.amp.EnumEmailAlert;
import cn.freemud.amp.OpenPushOrderConfig;
import cn.freemud.amp.body.OrderBody;
import cn.freemud.amp.constant.QueueMetadata;
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.OpenPlatformOrderPushServiceImpl;
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.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * All rights Reserved, Designed By www.freemud.com
 *
 * @version V1.0
 * @Title:
 * @Package: cn.freemud.consumer
 * @Descripttion:
 * @author: shuhu.hou
 * @date: 2019/4/26
 * @Copyright: 2017 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目.
 */
@AutoConfigureAfter(OpenPushOrderConfig.class)
@Component
public class OpenPushOrderConsumer {
    @Autowired
    private OpenPlatformOrderPushServiceImpl openPlatformOrderPushService;
    @Autowired
    private OrderPushLogMapper orderPushLogMapper;
    @Autowired
    private EmailAlertService emailAlertService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QueueMetadata.Order.OPEN_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(value = QueueMetadata.EXCHANGE_NAME, type = ExchangeTypes.TOPIC, durable = "true"), key = QueueMetadata.Order.OPEN_QUEUE_NAME_ROUTING_KEY),
            containerFactory = "rabbitListenerContainerFactory", admin = "rabbitAdmin")
    @RabbitHandler
    public void message(MQMessage<String> message) {
        JSONObject header = null;
        OrderBody orderBody = null;
        OrderPushLog orderPushLog = new OrderPushLog();
        String traceId = UUIDUtil.getUUID();
        try {
            orderBody = JSON.parseObject(message.getBody(), OrderBody.class);
            Date startDate = new Date();

            orderPushLog.setPushDate(startDate);
            orderPushLog.setOrderId(orderBody.getOrderBean().getOid());
            orderPushLog.setPartnerId(orderBody.getOrderBean().getCompanyId());
            orderPushLog.setRequestBody(JSON.toJSONString(orderBody));
            orderPushLog.setPlatformStoreId(orderBody.getOrderBean().getShopId());
            orderPushLog.setTraceId(traceId);
            orderPushLog.setBusiness("openStoreOrderPush");
            orderPushLog.setPushDate(startDate);
            SynchronizationOrderResponse synchronizationOrderResponse = openPlatformOrderPushService.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(), "OpenPushOrderConsumer异常", e);
            orderPushLog.setFailureReasons(e.getMessage().length() > 245 ? e.getMessage().substring(0, 240) : e.getMessage());
            orderPushLogMapper.insert(orderPushLog);
            emailAlertService.sendEmailAlert(EnumEmailAlert.Description.OrderPushError.getDescription(), e);
            return;
        }

    }

    public static String getErrorInfoFromException(Exception e) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return sw.toString();
        } catch (Exception e2) {
            return "bad getErrorInfoFromException";
        }
    }
}
