package com.ho.flow.monitor;

import com.ho.flow.entity.process.MovementDTO;
import com.ho.flow.feignclient.BusinessFeignClient;
import com.ho.flow.service.process.service.ProcessFlowNewService;
import com.ho.flow.threads.EventToProcessThread;
import com.ho.flow.util.EventToProcessThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author catkins
 * todo：告警转工单监听器类
 */
@Slf4j
@Configuration
public class EventToProcessMonitor {

    @Autowired
    private ProcessFlowNewService processFlowNewService;

    @Autowired
    private BusinessFeignClient businessFeignClient;

    @Value("${spring.activiti.initialDelay}")
    private Integer initialDelay;

    @Value("${spring.activiti.flag}")
    private Integer flag;

    /**
     * 监听告警队列是否有数据,如果有就生成工单
     */
    @PostConstruct
    public void run() {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
               // log.error("eventQueue:{}"+eventQueue);
                if ( eventQueue.size() > 0 ) {
                    MovementDTO movementDTO = getEvents();
                    // mysql入库队列是否有数据,有的话就调用入库方法
                    EventToProcessThreadPoolUtils newInstance = EventToProcessThreadPoolUtils.getNewInstance();
                    newInstance.executor(new EventToProcessThread(processFlowNewService,movementDTO,businessFeignClient));
                }
            }
        }, initialDelay, 1, TimeUnit.SECONDS);
    }

    /** 放生成好的告警數據隊列 */
    public static final ConcurrentLinkedQueue<MovementDTO> eventQueue = new ConcurrentLinkedQueue<MovementDTO>();

    public static final ReentrantLock eventQueueLock = new ReentrantLock();

    /**
     * 把生成的告警数据保存进队列
     * @param movementDTO
     */
    public void setEvents(MovementDTO movementDTO){
        eventQueueLock.lock();
        try{
            eventQueue.add(movementDTO);
            log.info("setEvents size:{}",eventQueue.size());
        } finally {
            eventQueueLock.unlock();
        }
    }

    /**
     * 从队列取数据
     * @return
     */
    public MovementDTO getEvents(){
        MovementDTO movementDTO = null;
        eventQueueLock.lock();
        try{
            movementDTO = eventQueue.poll();
            log.info("getEvents size:{}",eventQueue.size());
        } finally {
            eventQueueLock.unlock();
        }
        return movementDTO;
    }


}
