package com.yeejoin.amos.boot.module.jg.biz.event.listener;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.biz.event.CancellationEvent;
import com.yeejoin.amos.boot.module.jg.biz.event.listener.service.ManageStatusDataUpdateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Administrator
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CancellationEventListener {

    @Value("${cancellation.deal.thread.number:1}")
    private int threadNumber;

    private final BlockingQueue<String> queue = new LinkedBlockingQueue<>();

    private final ManageStatusDataUpdateService updateService;

    @EventListener(value = CancellationEvent.class)
    public void handleTransactionalEvent(CancellationEvent event) {
        log.info("收到作废消息:{}", JSONObject.toJSONString(event));
        List<String> records = event.getRecords();
        queue.addAll(records);

    }

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber, r -> {
            Thread t = new Thread(r);
            t.setName("CancellationWorker-" + t.getId());
            return t;
        });
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        String record = queue.take();
                        log.info("线程 {} 开始处理 record: {}", Thread.currentThread().getName(), record);
                        updateService.dealData(record, false);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });

        }
    }


}
