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

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.biz.reminder.biz.factory.QualityScoreUpdateFactory;
import com.yeejoin.amos.boot.module.jg.biz.reminder.core.event.EquipCreateOrEditEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
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;
import java.util.stream.IntStream;

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

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

    private final QualityScoreUpdateFactory qualityScoreUpdateFactory;

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

    private ExecutorService executorService;

    @TransactionalEventListener(value = EquipCreateOrEditEvent.class)
    @Async
    public void onEquipCreateOrEdit(EquipCreateOrEditEvent event) {
        log.info("数据质量等级处理器，收到设备装置数据保存消息:{}", JSONObject.toJSONString(event));
        queue.add(event);
    }

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


    private void processEvent(EquipCreateOrEditEvent event) {
        qualityScoreUpdateFactory.getUpdater(event.getEquipType()).update(event.getBizType(), event.getUpdatedIds());
    }
}
