package com.yeejoin.amos.boot.module.jxiop.biz.service.impl;

import cn.hutool.core.date.DateUtil;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanPointProcessVariableClassification;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 消费者线程
 *
 * @author jackyuj
 */

public class Consumer implements Runnable {

    private BlockingQueue<IdxBizFanPointProcessVariableClassification> queue = new LinkedBlockingQueue<>(5000);
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;

    //构造函数
    public Consumer(BlockingQueue<IdxBizFanPointProcessVariableClassification> queue, CommonServiceImpl commonService) {
        this.queue = queue;
        this.commonService = commonService;
    }

    public final String startTime = DateUtils.convertDateToString(DateUtil.beginOfYear(new Date()), DateUtils.DATE_TIME_PATTERN);
    public final String endTime = DateUtils.convertDateToString(DateUtils.getCurrentDayEndTime(new Date()), DateUtils.DATE_TIME_PATTERN);


    @Autowired
    CommonServiceImpl commonService;
    public void run() {
        Random r = new Random();
        boolean isRunning = true;
        try {
            while (isRunning) {
                IdxBizFanPointProcessVariableClassification poll = queue.poll();//有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回失败
                if (ObjectUtils.isNotEmpty(poll)) {
                    commonService.info(poll.getGatewayId(), startTime, endTime, poll);
                    Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));
                } else {
                    // 超过2s还没数据，认为所有生产线程都已经退出，自动退出消费线程。
                    isRunning = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            System.out.println("退出消费者线程！");
        }
    }
}