package com.kxs.product.biz.mq;

import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.product.api.amqp.rabbit.RabbitKxsOrderQueueMQ;
import com.kxs.system.api.dto.kxsapp.camp.CampAddBcqtTeamDTO;
import com.kxs.system.api.dto.kxsapp.camp.PrizePoolDTO;
import com.kxs.system.api.feign.RemoteSysService;
import com.kxs.system.api.feign.RemoteUserService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * rabbit 队列侦听器 商品下单过期队列
 *
 * @author Pota1ovO
 * @date 2024-05-07
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class RabbitKxsOrderQueueListener {
	private final RemoteSysService remoteSysService;

	/**
	 * 监听 老平台订单队列
	 *
	 * @param message 消息
	 */
	@RabbitListener(queues = RabbitKxsOrderQueueMQ.QUEUE_NAME, ackMode = "MANUAL")
	@RabbitHandler
	public void onMessage(String msg, Message message, Channel channel){
        try {
			log.info("收到客小爽订单消息: " + RabbitKxsOrderQueueMQ.parse(msg));
			RabbitKxsOrderQueueMQ.MsgEntity parse = RabbitKxsOrderQueueMQ.parse(msg);
			//处理百城千团订单，创建活动
			if(parse.getProductId() == 100 && parse.getStatus() == 2){
				CampAddBcqtTeamDTO campAddBcqtTeamDTO = new CampAddBcqtTeamDTO();
				campAddBcqtTeamDTO.setCaptainId(Long.valueOf(parse.getUserId()));
				campAddBcqtTeamDTO.setTeamName(parse.getRemark());
				remoteSysService.addBcqtTeam(campAddBcqtTeamDTO, SecurityConstants.FROM_IN);
			}
			//训练营订单处理
			if((parse.getStatus() == 2 || parse.getStatus() == 3)
					&& (parse.getProductId() == 10
					|| parse.getProductId() == 11
					|| parse.getProductId() == 77
					|| parse.getProductId() == 78
					|| parse.getProductId() == 79
					|| parse.getProductId() == 92
					|| parse.getProductId() == 27
					|| parse.getProductId() == 28
					|| parse.getProductId() == 39
					|| parse.getProductId() == 40
					|| parse.getProductId() == 10000) ){
				PrizePoolDTO prizePoolDTO = new PrizePoolDTO();
				BeanUtils.copyProperties(parse,  prizePoolDTO);
				remoteSysService.prizePoolIsRefreshed(prizePoolDTO, SecurityConstants.FROM_IN);
			}
			channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
			log.error("客小爽订单消息消费失败:{}", msg, e);
			try {
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			} catch (IOException ex) {
				log.error("客小爽订单消息手动确认失败" + ex.getMessage(), ex);
			}
        }
    }


}