package com.xxfc.platform.activity.handler;


import cn.hutool.json.JSONUtil;
import com.github.wxiaoqi.security.admin.dto.RegisterQueueDTO;
import com.rabbitmq.client.Channel;
import com.xxfc.platform.activity.biz.ActivityPopularizeBiz;
import com.xxfc.platform.activity.biz.ActivityUserJoinBiz;
import com.xxfc.platform.activity.config.RabbitActivityConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.*;
import java.util.concurrent.locks.StampedLock;

@Component
@Slf4j
public class PopularizeMQHandler {

    @Autowired
    ActivityPopularizeBiz activityPopularizeBiz;

    @Autowired
    ActivityUserJoinBiz activityUserJoinBiz;
    // 同时并发执行的线程数
    public static int threadTotal = 10;

    final Semaphore semaphore = new Semaphore(threadTotal);

    final CountDownLatch countDownLatch = new CountDownLatch(10);

    private final static StampedLock lock = new StampedLock();

    //@RabbitListener(queues = {RabbitActivityConfig.POPULARZIE_REGISTER_QUEUE,RabbitActivityConfig.POPULARZIE_AUTH_QUEUE})
    @RabbitListener(queues = {RabbitActivityConfig.POPULARZIE_0101_QUEUE})
    public void popularizeHandler(Message message, @Headers Map<String, Object> headers, Channel channel) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> {
            try {
                semaphore.acquire();
                    String messageId = message.getMessageProperties().getMessageId();
                    String msg = new String(message.getBody(), "UTF-8");
                    log.info("接收到的消息：msg = {}, 消息ID是：messageId = {} ", msg, messageId);
                    if (StringUtils.isNotBlank(msg)) {
                        long stamp = lock.writeLock();
                        try {
                            RegisterQueueDTO registerQueueDTO = JSONUtil.toBean(msg, RegisterQueueDTO.class);
                            activityPopularizeBiz.handleRegister(registerQueueDTO);
                        } finally {
                            lock.unlock(stamp);
                        }
                    }

                    Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
                    // 手动签收
                    channel.basicAck(deliveryTag, false);
                semaphore.release();
            } 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);
            }
            executorService.shutdown();
            countDownLatch.countDown();
        });
    }
    //新人注册有礼
    @RabbitListener(queues = {RabbitActivityConfig.ACTIVITY_NEW_QUEUE})
    public void activityNewHandler(Message message, @Headers Map<String, Object> headers, Channel channel) {
        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");
                    log.info("接收到的消息：msg = {}, 消息ID是：messageId = {} ", msg, messageId);

                    if (StringUtils.isNotBlank(msg)) {
                        RegisterQueueDTO registerQueueDTO = JSONUtil.toBean(msg, RegisterQueueDTO.class);
                        if(registerQueueDTO!=null&&(registerQueueDTO.getSign()==RegisterQueueDTO.SIGN_NEW||registerQueueDTO.getSign()==RegisterQueueDTO.SIGN_ACTIVATE)){
                            activityUserJoinBiz.joinActivity(registerQueueDTO.getAppUserId());
                        }

                    }

                    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);
                }
            }
        });
    }

}
