package com.ruoyi.trade.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.ruoyi.trade.domain.CTrademark;
import com.ruoyi.trade.service.ICTrademarkService;

/**
 * 商标数据入库队列
 *
 */
public class TrademarkSaveQueue {
	private static final Logger logger = LoggerFactory.getLogger(TrademarkSaveQueue.class);
	private ICTrademarkService cTrademarkService;

	private String threadName;
	private boolean collEd;
	private List<Thread> threads;

	/**
	 * add方法在添加元素的时候，若超出了度列的长度会直接抛出异常 put方法，若向队尾添加元素的时候发现队列已经满了会发生阻塞一直等待空间，以加入元素
	 * offer方法在添加元素时，如果发现队列已满无法添加的话，会直接返回false
	 * 
	 * poll: 若队列为空，返回null。 remove:若队列为空，抛出NoSuchElementException异常。
	 * take:若队列为空，发生阻塞，等待有元素。
	 */
	private LinkedBlockingQueue<CTrademark> queue;

	private volatile boolean running = true;

	public List<Thread> getThreads(){
		return threads;
	}
	private void send() {
		try {
//			CTrademark obj = queue.take();
			CTrademark obj = queue.poll();
			if (obj == null) {
				
//				logger.debug("队列中没有元素，休眠1秒");
				
				Thread.sleep(1000);
				return;
			}
			if (obj.getId() != null) {
				logger.debug("开始更新:" + new Gson().toJson(obj));
				cTrademarkService.updateById(obj);
			} else {
				logger.debug("开始保存:" + new Gson().toJson(obj));
				cTrademarkService.save(obj);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public int getSize() {
		return queue.size();
	}

	public void putQueue(CTrademark object) {
		boolean flag = queue.offer(object);
		if (!flag) {
			logger.warn("无法把数据加入到队列,因为队列已达到当前最大容量");
		}
	}

	public void setCollEd(boolean collEd) {
		this.collEd = collEd;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public TrademarkSaveQueue(Integer capacity, ICTrademarkService cTrademarkService) {

		this.cTrademarkService = cTrademarkService;
		this.queue = new LinkedBlockingQueue(capacity);
		this.threadName = Thread.currentThread().getName();
		this.collEd = false;
		this.threads = new ArrayList<Thread>();

		for (int i = 0; i < 20; i++) {
			Thread thread = new Thread(new Runnable() {
				public void run() {
					while (running) {
						try {
							if(collEd) {
								logger.debug("采集完成...");
								return;
							}
							send(); // write statistics
						} catch (Throwable t) {
							logger.error("保存数据时发生异常,原因: " + t.getMessage(), t);
							try {
								Thread.sleep(5000); // retry after 5 secs
							} catch (Throwable t2) {
							}
						}
					}
				}
			});

			this.threads.add(thread);
			thread.setDaemon(true);
			thread.setName(this.threadName + "-tst-" + i);
			thread.start();
		}

//		Thread thread2 = new Thread(new Runnable() {
//			public void run() {
//				while (running) {
//					try {
//						logger.debug("当前队列容量:[" + getSize() + "]");
//						try {
//							Thread.sleep(10000); // retry after 5 secs
//						} catch (Throwable t2) {
//						}
//					} catch (Throwable t) {
//						logger.error("保存数据时发生异常,原因," + t.getMessage(), t);
//						try {
//							Thread.sleep(5000); // retry after 5 secs
//						} catch (Throwable t2) {
//						}
//					}
//				}
//			}
//		});
//		thread2.setDaemon(true);
//		thread2.setName("TrademarkMonitorThread");
//		thread2.start();
		
		
//		for(Thread thread:this.threads) {
//			try {
//				thread.join();
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		}
//		
//		logger.debug("所有线程都同步完了，准备统计中间表,");
//		cTrademarkService.doSyncMark();
//		logger.debug("统计中间表完成");

	}

	public void close() {
		try {
			running = false;
		} catch (Throwable t) {
			logger.warn(t.getMessage(), t);
		}
	}

}
