package com.saga.thread.common;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSONObject;
import com.saga.util.MessageUtil;
import org.springframework.util.CollectionUtils;
import org.zillion.util.log.LogUtil;

import com.saga.entity.Record;
import com.saga.util.Constant;

/**
 * 写库
 *
 * @author 李井强
 */
public class WTDBThread extends Thread {

	private List<Record> wtdbrecordList = new ArrayList<Record>();
	public static long write = 0L;

	public WTDBThread() {
		try {
		} catch (Exception e) {
			LogUtil.error("WTDBThread.Exception: " + e.toString());
			System.exit(0);
		}
	}

	public void run() {
		LogUtil.info("WTDBThread-" + this.getName() + " Starting ...");
		while (true) {
			try {
				if (Constant.RecordListToDB.size() == 0) {
					Thread.sleep(10L);
					continue;
				}
				wtdbrecordList.addAll(Constant.RecordListToDB);
				Constant.RecordListToDB = new ArrayList<Record>();
				LogUtil.info("Constant.RecordListToDB remove " + wtdbrecordList.size());
				if (delayToDb()) {
					Thread.sleep(10L);
					continue;
				}
				Constant.BatchInsert(Constant.Database, wtdbrecordList);
				Constant.BatchInsertUpload(wtdbrecordList);
		//		sendMessage();
				write = System.currentTimeMillis();
				LogUtil.error("WTDBThread-" + this.getName() + ".write: " + write);
				wtdbrecordList = new ArrayList<Record>();
				Thread.sleep(10L);
			} catch (Exception e) {
				LogUtil.error("WTDBThread-" + this.getName() + ".run.Exception: " + e.toString());
			}
		}
	}

/*	ExecutorService executorService = Executors.newFixedThreadPool(10);
	private void sendMessage() {
		wtdbrecordList.forEach(record -> {
			//TODO 往activeMq消息队列里发送消息
			if (Constant.activeMqPointSet.contains(record.buildingSign + "-" + record.meterSign + "-" + record.funcID)) {
				executorService.execute(() -> {
					try {
						MessageUtil.sendMessage(JSONObject.toJSONString(record));
					} catch (Exception e) {
						LogUtil.error(e);
					}
				});
			}
		});
	}*/

	private boolean delayToDb() {
		if (wtdbrecordList.size() == 0
				|| (wtdbrecordList.size() < 500 && (System.currentTimeMillis() - this.write < Constant.delay))) {
			return true;
		}
		return false;
	}
}
