package com.junmp.jyzb.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.junmp.jyzb.api.bean.query.inAndOutRecordReq.OutInLogsReq;
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 OutInLogsReceiver {

    @Resource
    private LogSummaryService logSummaryService;
    /**
     * 日志记录的api
     */
    @Resource
    private LogRecordApi logRecordApi;
    @RabbitListener(queues = "orderResult")//监听队列名
    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("OrderResult");
        logRecordDTO.setRequestParams(msg);
        logRecordDTO.setLogType(30);
        logRecordDTO.setRequestUrl("queues = \"orderResult\"");
        try {
            System.out.println("msg = " + msg);
            // 创建日志对象

            // 手动确认消息
            channel.basicAck(deliveryTag, false);
            OutInLogsReq req = JSON.parseObject(msg, OutInLogsReq.class);
            //将消息进行消费
            Boolean result = logSummaryService.processInventoryRecords(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);
            }
        }
    }
}
