package com.tzy.listener.mq;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.tzy.common.constant.MqConstans;
import com.tzy.common.utils.DateUtils;
import com.tzy.dto.local.AllocateResult;
import com.tzy.pojo.card.CardGroupOrderInfo;
import com.tzy.sportcard.api.service.IAllocateGoodsService;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.teasoft.bee.osql.SuidRich;

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


@Slf4j
@Component
public class OrderAftAllocateConsumer {

	@Autowired
	private SuidRich suidRich;
	@Resource
	private IAllocateGoodsService allocateGoodsService;


	@RabbitHandler
	@RabbitListener(queuesToDeclare = @Queue(MqConstans.QUEUE_ORDER_AFT_ALLOCATE))
	public void orderAftAllocateConsumer(String param, Channel channel, Message message) throws IOException {
		orderAftAllocate(param);
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}

	private void orderAftAllocate(String param) {
		log.info("同步用户中卡,参数:{}", param);
		try {
			AllocateResult result = JSONObject.parseObject(param, AllocateResult.class);
			if (result.getOrderId() == null) {
				return;
			}
			CardGroupOrderInfo order = new CardGroupOrderInfo();
			order.setId(result.getOrderId());
			CardGroupOrderInfo existOrder = suidRich.selectOne(order);
			if (existOrder == null) {
				return;
			}
			order.setGoodsAllocate(1);
			order.setProp2(result.getGuessCount() > 0 ? result.getGuessCount().toString() : "0");
			order.setProp3(result.getMissCardCount() > 0 ? result.getMissCardCount().toString() : "0");
			order.setUpdateTime(DateUtils.getTimestampNow());
			suidRich.update(order);
			allocateGoodsService.aftAllocateOrderGoods(existOrder.getGroupInfoId());
		} catch (Exception e) {
			log.error("同步用户中卡异常,参数:{}", param, e);
		}
	}

}
