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.msl.common.base.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
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;

    @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());

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


        }
    }
}
