package com.gyee.alarm.task.thread;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gyee.common.contant.ContantXk;
import com.gyee.common.model.PointData;
import com.gyee.alarm.init.CacheContext;
import com.gyee.alarm.model.auto.ProBasicEquipment;
import com.gyee.alarm.model.auto.ProBasicEquipmentPoint;
import com.gyee.alarm.model.auto.ProEconInputOrOutputSpeed;
import com.gyee.alarm.service.auto.IProEconInputOrOutputSpeedService;
import com.gyee.alarm.util.DateUtils;
import com.gyee.alarm.util.StringUtils;
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 InputOrOutPutThreadPool implements Callable<String>, Serializable {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private static final long serialVersionUID = 0;
	private String unicode4hour="JKYC001";
	private String unicode1day="JKYC006";
	private String unicode3day="JKYC011";
	private String unicode7day="JKYC016";
	private String unicode1month="JKYC021";
	// 保存任务所需要的数据

	private Object threadPoolTaskData;
	private IEdosUtil edosUtil;
	private ProBasicEquipment wt;
	private Date begin;
	private Date end;

	private IProEconInputOrOutputSpeedService proEconInputOrOutputSpeedService;

	private static Map<String,Double> wtLastStatusMap=new HashMap<>();

	private static  Map<String, ProEconInputOrOutputSpeed> wtTimeStatusMap=new HashMap<>();
	public InputOrOutPutThreadPool(Object tasks, ProBasicEquipment wt,  Date begin, Date end,
								   IProEconInputOrOutputSpeedService proEconInputOrOutputSpeedService,IEdosUtil edosUtil) {

		this.threadPoolTaskData = tasks;
		this.wt = wt;
		this.begin = begin;
		this.end = end;
		this.proEconInputOrOutputSpeedService = proEconInputOrOutputSpeedService;
		this.edosUtil = edosUtil;

	}

	public synchronized String call() throws Exception {

		
		// 处理一个任务，这里的处理方式太简单了，仅仅是一个打印语句

		//System.out.println("开始执行任务：" + threadPoolTaskData);

		String result = "";

		// //便于观察，等待一段时间

		

		try {

			Map<String, ProBasicEquipmentPoint> pointmap= CacheContext.wtpAimap.get(wt.getId());

			QueryWrapper<ProEconInputOrOutputSpeed> queryWrapper = new QueryWrapper<>();
			queryWrapper.ge("record_date",begin).le("record_date",end).eq("windturbine_id",wt.getId());
			List<ProEconInputOrOutputSpeed> recordList = proEconInputOrOutputSpeedService.list(queryWrapper);
//            .stream()
//                    .filter(i -> i.getWindturbineId().equals(wt.getId())
//                            && (i.getRecordDate().compareTo(daybegin) == 0 || i.getRecordDate().after(daybegin))
//                            && (i.getRecordDate().compareTo(end) == 0 || i.getRecordDate().before(end))
//                           ).collect(Collectors.toList());

			if(!recordList.isEmpty())
			{
				for(ProEconInputOrOutputSpeed po:recordList)
				{
					wtTimeStatusMap.put(String.valueOf(po.getRecordDate().getTime()),po);
				}
			}

			double lastStatus=-1;


			ProBasicEquipmentPoint mxzt= pointmap.get(ContantXk.SBZT);
			ProBasicEquipmentPoint ssfs= pointmap.get(ContantXk.CJ_SSFS);

			//获取5分钟没个间隔1秒钟，保证状态与时序库保持一致
			List<PointData> statusls = edosUtil.getHistoryDatasSnap(mxzt.getNemCode(), begin.getTime() / 1000, end.getTime() / 1000,null,1L);
			List<PointData> ssfsls = edosUtil.getHistoryDatasSnap(ssfs.getNemCode(), begin.getTime() / 1000, end.getTime() / 1000,null,1L);


			if(!statusls.isEmpty() && !ssfsls.isEmpty() && ssfsls.size()==statusls.size())
			{
				List<ProEconInputOrOutputSpeed> ls=new ArrayList<>();
				for(int i=0;i<statusls.size();i++)
				{


					if(wtLastStatusMap.containsKey(wt.getId()))
					{
						lastStatus=wtLastStatusMap.get(wt.getId());
					}

					PointData statuspo=statusls.get(i);
					PointData ssfspo=ssfsls.get(i);
					double status= StringUtils.round(statuspo.getPointValueInDouble(),0);

					if(i==0)
					{
						lastStatus=status;
					}
					if (!Objects.equals(lastStatus, status))
					{

						//     切入切出风速
						if (lastStatus == 0 && status == 1)
						{
							ProEconInputOrOutputSpeed input = new ProEconInputOrOutputSpeed();

							input.setWindturbineId(wt.getId());
							input.setWindpowerstationId(wt.getWindpowerstationId());
							input.setProjectId(wt.getProjectId());
							input.setLineId(wt.getLineId());
							input.setRecordDate(DateUtils.truncate(new Date(statuspo.getPointTime())));
							input.setInputOrOutput(1);


							input.setSpeed(StringUtils.round(ssfspo.getPointValueInDouble(),2));

							if(!wtTimeStatusMap.containsKey(String.valueOf(statuspo.getPointTime())))
							{
								//roEconInputOrOutputSpeedService.save(input);
								ls.add(input);
							}
							lastStatus=status;

						}
						else if (lastStatus == 1 && status== 0)
						{
							ProEconInputOrOutputSpeed input = new ProEconInputOrOutputSpeed();
							input.setWindturbineId(wt.getId());
							input.setWindpowerstationId(wt.getWindpowerstationId());
							input.setProjectId(wt.getProjectId());
							input.setLineId(wt.getLineId());
							input.setRecordDate(DateUtils.truncate(new Date(statuspo.getPointTime())));
							input.setInputOrOutput(0);

							input.setSpeed(StringUtils.round(ssfspo.getPointValueInDouble(),2));

							if(!wtTimeStatusMap.containsKey(String.valueOf(statuspo.getPointTime())))
							{
								//proEconInputOrOutputSpeedService.save(input);

								ls.add(input);
							}
							lastStatus=status;
						}

						wtLastStatusMap.put(wt.getId(), status);

					}
				}


				proEconInputOrOutputSpeedService.saveBatch(ls);


			}


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		threadPoolTaskData = null;

		return result;

	}


}