package com.clx.performance.listener;

import com.clx.performance.constant.RabbitKeyConstants;
import com.clx.performance.dao.OrderGoodsDao;
import com.clx.performance.enums.OrderGoodsStatusEnum;
import com.clx.performance.model.OrderGoods;
import com.clx.performance.service.IntegralMqService;
import com.clx.performance.service.linewarn.LineWarnMqService;
import com.msl.common.base.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 处理货单由状态已挂单变为挂单中
 */
@Slf4j
@Component
public class RabbitOrderGoodsStatusOnHandler {

    @Autowired
    private OrderGoodsDao orderGoodsDao;

    @Autowired
    private IntegralMqService integralMqService;
    @Autowired
    private LineWarnMqService lineWarnMqService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitKeyConstants.ORDER_GOODS_ON_DEAD_QUEUE)
    public void onMessage(String message) {
        log.info("处理货单状态由已挂单变为挂弹中监听器执行,货单ID为{}", message);
        if (StringUtils.isBlank(message)) {
            return;
        }
        Optional<OrderGoods> optional = orderGoodsDao.getByOrderGoodsNo(message);
        if (!optional.isPresent()) {
            log.info("处理货单状态由已挂单变为挂单中监听器未查询到货单数据,消息为{}", message);
            return;
        }
        OrderGoods orderGoods = optional.get();
        if (OrderGoodsStatusEnum.Status.CREATED.getCode().equals(orderGoods.getOrderGoodsStatus())) {
            log.info("处理货单状态由已挂单变为挂单中监听器执行,从状态{}-----变更为{}", orderGoods.getOrderGoodsStatus(), OrderGoodsStatusEnum.Status.PAYING.getName());
            orderGoodsDao.updateOrderGoodsStatusByOrderGoodsNo(orderGoods.getOrderGoodsNo(), OrderGoodsStatusEnum.Status.PAYING.getCode());


            Message orderNoMessage = MessageBuilder.withBody(orderGoods.getOrderNo().getBytes()).build();

            //发送mq，更改货单对应的订单为挂单中
            rabbitTemplate.send(
                    RabbitKeyConstants.ORDER_POSTED_EXCHANGE, RabbitKeyConstants.ORDER_POSTED_ROUTE_KEY, orderNoMessage
            );

            // 发送mq
            lineWarnMqService.orderGoodsAdd(orderGoods.getOrderGoodsNo());

            // 添加积分货单
            try {
                integralMqService.orderGoodsAdd(orderGoods.getOrderGoodsNo(),
                        orderGoods.getSendAddressId(), orderGoods.getSendAddressShorter(),
                        orderGoods.getReceiveAddressId(), orderGoods.getReceiveAddressShorter());
            }catch (Exception e) {
                log.error(ExceptionUtils.getStackTrace(e));
            }


        }
    }
}
