package com.tzy.listener.mq;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.tzy.common.constant.Constants;
import com.tzy.common.constant.MqConstans;
import com.tzy.common.dto.group.SyncUserWinCardDTO;
import com.tzy.framework.util.RedisUtils;
import com.tzy.sportcard.api.service.IAppUserWinCardService;
import com.tzy.sportcard.api.service.ICardReportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;


/**
 * es 卡密数据同步
 */
@Slf4j
@Component
public class UserWinCardConsumer {
	@Resource
	private IAppUserWinCardService appUserWinCardService;
	@Resource
	private RedisUtils redisUtils;

	@RabbitHandler
	@RabbitListener(queuesToDeclare = @Queue(MqConstans.QUEUE_SYNC_USER_WIN_CARD))
	public void syncUserWinCardConsumer(String param, Channel channel, Message message) throws IOException {
		log.info("同步用户中卡,参数:{}", param);
		String key="win_card_count_" + param;
		long count = redisUtils.incr(key, 1);
		redisUtils.expire(key, 30);
		try {
			SyncUserWinCardDTO syncParam = JSONObject.parseObject(param, SyncUserWinCardDTO.class);
			if (Constants.ORDER_TYPE_GROUP.equals(syncParam.getType())) {
				appUserWinCardService.syncGroupWindCard(syncParam.getIds());
			} else {
				appUserWinCardService.syncShopOrderWindCard(syncParam.getIds());
			}
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (Exception e) {
			log.error("同步用户中卡异常,参数:{}", param, e);
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), count<3);
		}
	}

}
