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.IdxBizPvPointProcessVariableClassification;
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 ConsumerPv implements Runnable {

    private BlockingQueue<IdxBizPvPointProcessVariableClassification> queue = new LinkedBlockingQueue<>(5000);
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;
    String startTime1 = DateUtils.convertDateToString(DateUtil.beginOfYear(new Date()), DateUtils.DATE_TIME_PATTERN);
    String endTime1 = DateUtils.convertDateToString(DateUtils.getCurrentDayEndTime(new Date()), DateUtils.DATE_TIME_PATTERN);
    //构造函数
    public ConsumerPv(BlockingQueue<IdxBizPvPointProcessVariableClassification> queue, CommonServiceImpl commonService, String startTime, String endTime) {
        this.queue = queue;
        this.commonService = commonService;
        this.startTime1 = startTime;
        this.endTime1 = endTime;
    }


    @Autowired
    CommonServiceImpl commonService;
    public void run() {
        Random r = new Random();
        boolean isRunning = true;
        try {
            while (isRunning) {
                IdxBizPvPointProcessVariableClassification poll = queue.poll();//有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回失败
                if (ObjectUtils.isNotEmpty(poll)) {
                    commonService.infoPv(poll.getGatewayId(), startTime1, endTime1, 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("退出消费者线程！");
        }
    }
}