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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.SnowflakeIdUtil;
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.InspectionDetectionInfoUpdateService;
import com.yeejoin.amos.boot.module.jyjc.biz.event.publisher.BizEmqPublisher;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.entity.InspectionDetectionInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.ymt.api.mapper.InspectionDetectionInfoMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
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.Collectors;

/**
 * @author Administrator
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class InspectionDetectionSaveToDbEventListener implements ApplicationListener<InspectionDetectionSaveToDbEvent> {

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

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

    private final InspectionDetectionInfoUpdateService  updateService;


    @Override
    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.update(jyjcInspectionResult);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });
        }
    }







}
