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.UseInfoSaveToDbEvent;
import com.yeejoin.amos.boot.module.ymt.api.mapper.UseInfoMapper;
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 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
public class UseInfoSaveToDbEventListener implements ApplicationListener<UseInfoSaveToDbEvent> {

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

    @Autowired
    UseInfoMapper useInfoMapper;

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

    @Override
    public void onApplicationEvent(UseInfoSaveToDbEvent 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();
                        //更新使用信息表
                        useInfoMapper.updateByRecord(jyjcInspectionResult.getEquipUnicode(), jyjcInspectionResult.getNextInspectionDate(), jyjcInspectionResult.getInspectionType(), jyjcInspectionResult.getApplicationNo());
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            });

        }
    }
}
