package com.gyee.alarm.task.thread;

import com.gyee.alarm.feigns.IAlarmService;
import com.gyee.alarm.model.vo.AlarmCustomTag;
import com.gyee.alarm.model.vo.AlarmTag;
import com.gyee.alarm.model.vo.AlarmTypeValue;
import com.gyee.alarm.model.vo.DeviceTypeValue;
import com.gyee.alarm.rule.AlarmFunction;
import com.gyee.alarm.rule.expression.AlarmExpression;
import com.gyee.alarm.rule.expression.Analyzer;
import com.gyee.common.model.PointData;
import com.gyee.alarm.util.realtimesource.IEdosUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.Callable;

public class AlarmThreadPool implements Callable<String>, Serializable {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private static final long serialVersionUID = 0;

	// 保存任务所需要的数据

	private Object threadPoolTaskData;



	private IAlarmService alarmService;

	private List<AlarmCustomTag> alarmVoList;
	private StringBuilder str;

	private Integer interval;

	private Integer readRows;


	public AlarmThreadPool(Object tasks,  IAlarmService alarmService, List<AlarmCustomTag> alarmVoList,
						   Integer interval, StringBuilder str,Integer readRows
	) {

		this.threadPoolTaskData = tasks;
		this.alarmService = alarmService;
		this.alarmVoList = alarmVoList;
		this.interval = interval;
		this.str = str;
		this.readRows = readRows;
	}

	public synchronized String call() throws Exception {

		String result = "";

		try {

			while (true)
			{

				List<AlarmTag>  saveAlarmTags=new ArrayList<>();
				List<AlarmTag>  updateAlarmTags=new ArrayList<>();
				for(AlarmCustomTag vo:alarmVoList)
				{

					checkRule(saveAlarmTags,updateAlarmTags,vo);

					logger.info(String.valueOf(threadPoolTaskData)+"新增报警数量：" + saveAlarmTags.size());
					logger.info(String.valueOf(threadPoolTaskData)+"结束报警数量：" + updateAlarmTags.size());
				}

				if(!saveAlarmTags.isEmpty())
				{
					alarmService.saveAlarm(saveAlarmTags);
				}

				if(!saveAlarmTags.isEmpty())
				{
					alarmService.updateAlarm(updateAlarmTags);
				}


				try {
					Thread.sleep((interval * 1000));
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}

		} catch (Exception e) {

			e.printStackTrace();
		}
		threadPoolTaskData = null;

		return result;

	}

	private void checkRule(List<AlarmTag>  saveAlarmTags,List<AlarmTag>  updateAlarmTags,AlarmCustomTag ar) {


		try {

			AlarmExpression alarmExpression = Analyzer.getAlarmExpression(ar.getTagId());

			AlarmFunction alarmFunction=null;

			if (ar.getDevicetype().equals(DeviceTypeValue.WT.getCode()) ) {
				 alarmFunction = new AlarmFunction(alarmExpression, DeviceTypeValue.WT, ar.getDeviceid());



			}else if (ar.getDevicetype().equals(DeviceTypeValue.WP.getCode()) ) {
				 alarmFunction = new AlarmFunction(alarmExpression, DeviceTypeValue.WP, ar.getStationid());


			}else if (ar.getDevicetype().equals(DeviceTypeValue.BT.getCode()) ) {
				 alarmFunction = new AlarmFunction(alarmExpression, DeviceTypeValue.BT, ar.getStationid());


			}

			try {

                    Object obj = alarmFunction.explain();
                    if (obj instanceof Boolean) {

                        if (true == (boolean) obj) {

							AlarmTag po=new AlarmTag();
							po.setId(ar.getId());
							po.setTs(new Date().getTime());
							po.setEndts(new Date().getTime());
							po.setVal(1.0);
							po.setTimeLong(0.0);

							saveAlarmTags.add(po);

                        } else {
							AlarmTag po=new AlarmTag();
							po.setId(ar.getId());
							po.setTs(new Date().getTime());
							po.setEndts(new Date().getTime());
							po.setVal(0.0);
							po.setTimeLong(0.0);

							updateAlarmTags.add(po);
                        }
                    } else {
                       // System.out.print(obj.toString());
                    }
                } catch (Exception ex) {
                   // ex.printStackTrace();
				logger.error("自定义报警规则执行时出错！"+alarmFunction.getThingId()+"--"+ar.getTagId()+"----" + ex.getMessage());
                }

		} catch (Exception ex) {
			logger.error("生成自定义报警规则失败！规则id：" + ar.getId());
		}
	}

}