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

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.biz.event.ChangeDataEvent;
import com.yeejoin.amos.boot.module.jg.biz.event.handler.IChangeUpdateHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

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;
import java.util.stream.IntStream;

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

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

    private final List<IChangeUpdateHandler<ApplicationEvent>> changeUpdateHandlers;

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


    @TransactionalEventListener(value = ChangeDataEvent.class)
    @Async
    public void handleTransactionalEvent(ChangeDataEvent event) {
        log.info("收到用户变更业务数据消息:{}", JSONObject.toJSONString(event));
        queue.add(event);
    }

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        IntStream.range(0, threadNumber).forEach(i -> {
            executorService.execute(() -> {
                while (true) {
                    try {
                        ChangeDataEvent event = queue.take();
                        processEvent(event);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });
        });
    }

    private void processEvent(ChangeDataEvent event) {
        changeUpdateHandlers.stream().filter(h -> h.supports(event)).forEach(h -> h.handle(event));
    }
}

