package com.xxfc.platform.vehicle.mqhandler;


import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.xxfc.platform.vehicle.biz.CompanyInfoBiz;
import com.xxfc.platform.vehicle.biz.VehiclePublishReceiveBiz;
import com.xxfc.platform.vehicle.entity.CompanyInfo;
import com.xxfc.platform.vehicle.pojo.dto.VehicleReceiveRefundDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.xxfc.platform.vehicle.config.RabbitVehicleConfig.VEHICLE_CORPORATION_UPD_QUEUE;
import static com.xxfc.platform.vehicle.config.RabbitVehicleConfig.VEHICLE_RECEVIE_REFUND_QUEUE;

@Component
@Slf4j
public class VehicleReceiveMQHandler {

    @Autowired
    VehiclePublishReceiveBiz  publishReceiveBiz;



    /**
     * 接单退款信息
     * @param
     */
    @RabbitListener(queues = VEHICLE_RECEVIE_REFUND_QUEUE)
    public void integralHandler(Message message, @Headers Map<String, Object> headers, Channel channel) {
        log.info("接单退款信息 messageJson："+ JSONUtil.parse(message));
        try {
            Thread.sleep(2000L);
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String messageId = message.getMessageProperties().getMessageId();
                    String msg = new String(message.getBody(), "UTF-8");
                    VehicleReceiveRefundDTO receiveRefundDTO = JSONUtil.toBean(msg, VehicleReceiveRefundDTO.class);
                    publishReceiveBiz.refundReceiveQueue(receiveRefundDTO);
                    executorService.shutdown();
                    Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
                    // 手动签收
                    channel.basicAck(deliveryTag, false);
                } catch (Exception e) {
                    log.info("接收到的消息失败");
                    try {
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                    } catch (IOException i) {
                        log.error(e.getMessage(), i);
                    }
                    log.error(e.getMessage(), e);
                }
            }
        });
    }
}
