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

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionResult;
import com.yeejoin.amos.boot.module.jyjc.biz.event.InspectionDetectionSaveToDbEvent;
import com.yeejoin.amos.boot.module.jyjc.biz.event.listener.service.InspectionResultProcessor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.PostConstruct;
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 InspectionDetectionSaveToDbEventListener {

    @Value("${inspect.info.save.thread.number:3}")
    private int threadNumber;

    private final BlockingQueue<JyjcInspectionResult> blockingQueue = new LinkedBlockingQueue<>();

    private final InspectionResultProcessor updateService;


    @TransactionalEventListener(value = InspectionDetectionSaveToDbEvent.class)
    public void onApplicationEvent(InspectionDetectionSaveToDbEvent event) {
        log.info("收到检验检测信息插入或者更新消息:{}", JSONObject.toJSONString(event.getJyjcInspectionResultList()));
        blockingQueue.addAll(event.getJyjcInspectionResultList());
    }

    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newFixedThreadPool(threadNumber);
        for (int i = 0; i < threadNumber; i++) {
            executorService.execute(() -> {
                while (true) {
                    try {
                        JyjcInspectionResult jyjcInspectionResult = blockingQueue.take();
                        updateService.process(jyjcInspectionResult);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });
        }
    }


}
