package com.tzy.listener.mq;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.tzy.common.constant.MqConstans;
import com.tzy.elasticsearch.dto.CardGroupInfoGoodsDTO;
import com.tzy.elasticsearch.service.CardGroupInfoGoodsService;
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 GoodsSyncEsConsumer {
	@Resource
	private CardGroupInfoGoodsService cardGroupInfoGoodsService;

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

	private void syncEsGoods(String param) {
		log.info("同步组团卡密ES,参数:{}", param);
		try {
			CardGroupInfoGoodsDTO syncParam = JSONObject.parseObject(param, CardGroupInfoGoodsDTO.class);
			if(CardGroupInfoGoodsDTO.SYNC_TYPE_ADD.equals(syncParam.getSyncType())){
				cardGroupInfoGoodsService.save(syncParam.getGroupInfoId());
			}else if(CardGroupInfoGoodsDTO.SYNC_TYPE_EDIT.equals(syncParam.getSyncType())){
				cardGroupInfoGoodsService.update(syncParam);
			}else if(CardGroupInfoGoodsDTO.SYNC_TYPE_DEL_ADD.equals(syncParam.getSyncType())){
				cardGroupInfoGoodsService.syncInfo(syncParam.getGroupInfoId());
			}
		} catch (Exception e) {
			log.error("同步组团卡密ES异常,参数:{}", param, e);
		}

	}


}
