package com.junmp.jyzb.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.junmp.jyzb.api.bean.query.InAndOutRecordReq.CabinetLogsRecordReq;
import com.junmp.jyzb.service.LogSummaryService;
import com.junmp.v2.log.api.LogRecordApi;
import com.junmp.v2.log.api.bean.dto.LogRecordDto;
import com.junmp.v2.log.api.constant.LogConstant;
import com.junmp.v2.log.api.enums.LogTypeEnum;
import com.junmp.v2.log.api.factory.LogRecordFactory;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

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

/**
 * 单警柜上报出入库记录监听消息队列
 */
@Component
public class OutInLogsByCabinetReceiver {

    @Resource
    private LogSummaryService logSummaryService;
    /**
     * 日志记录的api
     */
    @Resource
    private LogRecordApi logRecordApi;
    @RabbitListener(queues = "CabinetLogsRecord")//监听队列名
    private void a(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){
        // 创建日志对象
        LogRecordDto logRecordDTO = LogRecordFactory.createLogRecord(LogConstant.LOG_DEFAULT_NAME, "CabinetLogsRecord");

        logRecordDTO.setLogType(LogTypeEnum.OPT_LOG.getCode());
        logRecordDTO.setHttpMethod("RabbitMQ");
        logRecordDTO.setLogContent("CabinetLogsRecord");
        logRecordDTO.setRequestParams(msg);
        logRecordDTO.setLogType(30);
        logRecordDTO.setRequestUrl("queues = \"CabinetLogsRecord\"");
        try {
            System.out.println("msg = " + msg);

            // 手动确认消息
            channel.basicAck(deliveryTag, false);
            CabinetLogsRecordReq req = JSON.parseObject(msg, CabinetLogsRecordReq.class);
            //将消息进行消费
            Boolean result = logSummaryService.processOutInRecords(req);
            logRecordDTO.setRequestResult(result.toString());
            logRecordApi.addAsync(logRecordDTO);
        } catch (Exception e) {
            // 处理消息过程中发生异常，拒绝消息并将其重新放回队列ms
            try {
                channel.basicNack(deliveryTag, false, true);
                logRecordDTO.setRequestResult(e.getMessage().toString());
                logRecordApi.addAsync(logRecordDTO);
            } catch (IOException ex) {
                logRecordDTO.setRequestResult(ex.getMessage().toString());
                logRecordApi.addAsync(logRecordDTO);
                throw new RuntimeException(ex);
            }
        }
    }
}
