package cn.freemud.service.impl;

import cn.freemud.amp.config.DlPayQueryMqConfig;
import cn.freemud.amp.config.DlPaymentMqConfig;
import cn.freemud.amqp.Header;
import cn.freemud.amqp.MQAction;
import cn.freemud.amqp.MQMessage;
import cn.freemud.amqp.MQService;
import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.entities.dto.OrderPrintDto;
import cn.freemud.entities.dto.pay.PaymentMqMessageDto;
import cn.freemud.redis.RedisCache;
import cn.freemud.utils.AppLogUtil;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.config.TopicExchangeConfig;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.sdk.api.assortment.order.request.order.OrderStatusChangeRequestDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class OrderQueueService {

    @Autowired
    private MQService mqService;
    @Autowired
    private RedisCache redisCache;


    private static final String backOrdersChangeOrderStatusConsumerQueue = "program.backorders_change_order_status_consumer_queue";
    private static final String backOrdersNotifyActivityExchange = "program.backorders_notify_activity_exchange";

    @Value("${mq.queue.cloud_print_queue}")
    private String cloudPrintQueue;
    @Value("${mq.cloud_print_exchange}")
    private String cloud_print_exchange;


    public void backOrdersNotifyActivity(OrderBeanV1 orderBean) {
        String oid = orderBean.getOid();
        Integer statusV1 = orderBean.getStatus();
        this.backOrdersStatusChange(oid, statusV1, orderBean.getCompanyId());
    }

    public void backOrdersStatusChange(OrderBeanV1 orderBean) {
        this.backOrdersStatusChange(orderBean.getOid(), orderBean.getStatus(),orderBean.getPayStatus(), orderBean.getCompanyId());
    }

    /**
     * 失败订单冲正 mq
     */
    public void backOrdersStatusChange(String oid, Integer orderStatus, Integer payStatus, String partnerId) {
        if (StringUtils.isEmpty(oid)) {
            return;
        }
        AppLogUtil.infoLog("backOrdersStatusChange oid:{} orderStatus:{}", oid, String.valueOf(orderStatus));
        OrderStatusChangeRequestDto requestDto = new OrderStatusChangeRequestDto();
        requestDto.setOid(oid);
        requestDto.setPayStatus(payStatus);
        requestDto.setOrderStatus(orderStatus);
        requestDto.setPartnerId(partnerId);

        try {
            Header header = new Header(MQAction.INSERT.getAction(), "backOrdersStatusChange", oid, backOrdersChangeOrderStatusConsumerQueue);
            MQMessage<OrderStatusChangeRequestDto> message = new MQMessage<>(header, requestDto);
            mqService.convertAndSend(backOrdersNotifyActivityExchange, backOrdersChangeOrderStatusConsumerQueue, message);
        } catch (Exception e) {
            AppLogUtil.errorLog("ActivityReverse", JSON.toJSONString(requestDto), "", e);
        }
    }


    public void backOrdersStatusChange(String oid, Integer orderStatusV1, String partnerId) {
        if (StringUtils.isEmpty(oid)) {
            return;
        }
        AppLogUtil.infoLog("backOrdersStatusChange oid:{} orderStatus:{}", oid, String.valueOf(orderStatusV1));
        OrderStatusChangeRequestDto requestDto = new OrderStatusChangeRequestDto();
        requestDto.setOid(oid);
        requestDto.setOrderStatus(orderStatusV1);
        requestDto.setPartnerId(partnerId);

        try {
            Header header = new Header(MQAction.INSERT.getAction(), "backOrdersStatusChange", oid, backOrdersChangeOrderStatusConsumerQueue);
            MQMessage<OrderStatusChangeRequestDto> message = new MQMessage<>(header, requestDto);
            mqService.convertAndSend(backOrdersNotifyActivityExchange, backOrdersChangeOrderStatusConsumerQueue, message);
        } catch (Exception e) {
            AppLogUtil.errorLog("ActivityReverse", JSON.toJSONString(requestDto), "", e);
        }

        String redisKey = RedisKeyConstant.KGD_PAYMENT_CANCEL_OID + oid;
        //取消支付订单缓存
        redisCache.save(redisKey, true, 120L, TimeUnit.MINUTES);
    }


    /**
     * 发MQ去打印
     */
    public void asynchronousPrint(OrderPrintDto request) {
//        AppLogUtil.debugLog("OrderPrintDto", JSONObject.toJSONString(request), null);
        Header header = new Header(MQAction.INSERT.getAction(), "asynchronous-print-api", request.getOid() + "", cloudPrintQueue);
        MQMessage<OrderPrintDto> message = new MQMessage<>(header, request);
        mqService.convertAndSend(cloud_print_exchange, cloudPrintQueue, message);
    }

    /**
     * 发支付补偿mq，查询支付结果回调支付成功接口
     */
    public void paymentCallback(PaymentMqMessageDto dto) {
        MQMessage<PaymentMqMessageDto> mqMessage = new MQMessage<PaymentMqMessageDto>();
        mqMessage.setBody(dto);
        Integer ttl = 20 * 1000;
        Header header = new Header();
        header.setKey("1");
        mqMessage.setHeader(header);
        byte[] notifyMsgBytes = JSON.toJSONString(mqMessage).getBytes();
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setExpiration(ttl.toString());
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        Message delmessage = new Message(notifyMsgBytes, messageProperties);
        mqService.convertAndSend(TopicExchangeConfig.EXCHANGE_NAME, DlPaymentMqConfig.OPEN_STORE_PAYMENT_QUERY_DL_KEY, delmessage);
    }

    /**
     * 发支付补偿mq，查询支付结果回调支付成功接口
     */
    public void putPayQueryDelMq(PaymentMqMessageDto dto) {
        MQMessage<PaymentMqMessageDto> mqMessage = new MQMessage<PaymentMqMessageDto>();
        mqMessage.setBody(dto);
        Header header = new Header();
        header.setKey("1");
        mqMessage.setHeader(header);
        byte[] notifyMsgBytes = JSON.toJSONString(mqMessage).getBytes();
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setExpiration("5000"); //5秒
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        mqService.convertAndSend(TopicExchangeConfig.EXCHANGE_NAME, DlPayQueryMqConfig.KGD_PAY_QUERY_DL_KEY, new Message(notifyMsgBytes, messageProperties));
    }
}
