package org.springblade.payment.listener.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.constant.OrderConstant;
import org.springblade.common.enums.AppConstant;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.ldt.bills.service.IBillsService;
import org.springblade.payment.entity.SuccessParams;
import org.springblade.payment.handle.handler.CancelTradeHandle;
import org.springframework.amqp.core.Message;
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 java.io.IOException;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 16:15 2021/11/1
 * @Modified By:
 */
@Component
@Slf4j
public class OrderListener {
	@Autowired
	private CancelTradeHandle cancelTradeHandle;

	@Autowired
	private IBillsService billsService;

	@Autowired
	private BladeLogger bladeLogger;

	/**
	 * 接收消息
	 */
	@RabbitHandler
	@RabbitListener(queues = OrderConstant.DLX_ORDER_QUEUE)
	public void listen(String successParamsJSON,Message message, Channel channel) throws IOException {
		log.info("person 接收到消息=[{}]", message.toString());
		bladeLogger.info("person 接收到消息=[{}]", message.toString());
		try {
			//解析参数
			SuccessParams successParams = JSONObject.parseObject(successParamsJSON, SuccessParams.class);
			//获取账单信息
			Bills bills = billsService.getById(successParams.getBills().getId());
			//判断支付状态
			if(ObjectUtils.isNotEmpty(bills) && StringUtils.equals(bills.getPayStatus(), AppConstant.BillPayStatus.待付款.name())){
				//发送取消信息队列
				cancelTradeHandle.handle(successParams);
			}
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		} catch (IOException e) {
			//失败后重新放回队列  不推荐，如果服务因为某种暂时无法恢复原因失败，那么会一直循环回归队列--->消费失败
		 	channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
			// 丢弃消息
			//channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
			//失败后消息被确认,
//			channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
			log.error("订单消息错误:{}", e.getMessage());
			bladeLogger.error("订单消息错误:{}", e.getMessage());
		}
	}
}
