package com.yida.data.system.configure;

import com.rabbitmq.client.Channel;
import com.yida.data.common.core.entity.WxPublicQr;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.rabbit.constant.RabbitConstant;
import com.yida.data.system.dto.QywxCallbackHandleDTO;
import com.yida.data.system.service.EduAgentWxPublicReceiverService;
import com.yida.data.system.service.QywxHandleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 企业微信回调mq处理类
 *
 * @author ZYJ
 * @date 2023/10/26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class QywxHandleRabbitReceiver {

    private final QywxHandleService qywxHandleService;

    /**
     * 企业微信处理接收者
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(RabbitConstant.QYWX_HANDLE_QUEUE),
            exchange = @Exchange(RabbitConstant.QYWX_HANDLE_EXCHANGE)
    ))
    public void qywxHandleRabbitReceiver(QywxCallbackHandleDTO dto, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 处理企业微信回调信息
            switch (dto.getQywxCallbackTypeEnum()) {
                // 自开发回调
                case POST:
                    qywxHandleService.handlePostCallback(dto);
                    break;
                // 代开发应用模板回调
                case POST_NORMAL:
                    qywxHandleService.handlePostNormalCallback(dto);
                    break;
                // 处理企业微信代开发应用回调信息
                case POST_EVENT:
                    qywxHandleService.handlePostEventCallback(dto);
                    break;
                default:
                    throw new FebsException("回调类型错误");
            }
        } catch (Exception e) {
            log.error("rabbitmq处理企业微信回调消息失败, msg: {}", dto, e);
            // 重新回到队列
//            channel.basicNack(deliveryTag, false, true);
        } finally {
            // 确认收到消息，只确认当前消费者的一个消息收到
            channel.basicAck(deliveryTag, false);
        }
    }
}
