package com.junmp.jyzb.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.junmp.jyzb.api.bean.query.InAndOutRecordReq.CabinetLogsRecordReq;
import com.junmp.jyzb.service.InventorySummaryService;
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 CabinetLogReceiver {
    @Resource
    private InventorySummaryService inventorySummaryService;
    /**
     * 日志记录的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 {
            // 手动确认消息
            channel.basicAck(deliveryTag, false);
            CabinetLogsRecordReq req = JSON.parseObject(msg, CabinetLogsRecordReq.class);
            //将消息进行消费
            Boolean result = inventorySummaryService.cabinetInOutRecords(req);
            logRecordDTO.setRequestResult(result.toString());
            logRecordApi.addAsync(logRecordDTO);
        } catch (Exception e) {
            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);
            }
        }
    }
}
