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

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.jg.biz.event.CancellationAndGradeEvent;
import com.yeejoin.amos.boot.module.jg.biz.event.dto.CancelEquipItem;
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 CancelAndGradeEventListener {

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

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

    private final ManageStatusDataUpdateService updateService;

    @EventListener(value = CancellationAndGradeEvent.class)
    public void handleTransactionalEvent(CancellationAndGradeEvent event) {
        log.info("收到作废且更新评分消息:{}", JSONObject.toJSONString(event));
        List<String> records = event.getRecords();
        CancelEquipItem cancelEquipItem = new CancelEquipItem();
        cancelEquipItem.setRecords(records);
        cancelEquipItem.setProjectContraptionIds(event.getProjectContraptionIds());
        queue.add(cancelEquipItem);
    }


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

        }
    }


}
