package com.gyee.frame.util.mongodb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gyee.frame.common.spring.InitialRunner;
import com.gyee.frame.model.auto.RMConfig;
import com.gyee.frame.model.custom.PointData;
import com.gyee.frame.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 */
public class UpdateDataUtil {



	private String po_key = "S";

	// private Logger logger = Logger.getLogger(this.getClass().getName());

	


	@SuppressWarnings("unchecked")
	public void updateData(PointData point, JedisPool jedisPool_ss, JedisPool jedisPool_db) throws Exception {

		if (StringUtils.isNotNull(point) && StringUtils.isNotNull(point.getEdnaId()) && StringUtils.isNotNull(point.getPointTime()) && StringUtils.isNotNull(point.getPointValueInDouble())) {
			
			if ( InitialRunner.rmcmap.containsKey(point.getEdnaId())) {
				
				Date queryDate = new Date(point.getPointTime() * 1000);
				
				RMConfig rmc = InitialRunner.rmcmap.get(point.getEdnaId());

				Calendar cal = Calendar.getInstance();
				cal.set(Calendar.HOUR_OF_DAY, 0);
				cal.set(Calendar.MINUTE, 0);
				cal.set(Calendar.SECOND, 0);
				cal.set(Calendar.MILLISECOND, 0);

				Date begin = cal.getTime();
				cal.add(Calendar.DAY_OF_MONTH, 1);
				Date end = cal.getTime();
				// 当前日期
				if (queryDate.getTime() >= (begin.getTime()) && queryDate.getTime() <= (end.getTime())) {

					Map<String, Object> rm =new HashMap<String, Object>();
					rm.put(String.valueOf(point.getPointTime()),point.getPointValueInDouble() );
					
					Jedis rmjedis =jedisPool_ss.getResource();
					rmjedis.select(rmc.getRedisindex());
					rmjedis.set(point.getEdnaId(), JSON.toJSONString(rm));
					rmjedis.close();
					if (StringUtils.isNotNull(rmc.getUkey()) && StringUtils.isNotNull(rmc.getMongodbindex())) {
						Jedis jedis = jedisPool_db.getResource();
						jedis.select(rmc.getMongodbindex());
						String str = jedis.hget(String.valueOf(rmc.getUkey()),"1");
						JSONArray array = JSONArray.parseArray(str);
						
						int state=0;
						
							for (int i = 0; i < array.size(); i++) {
								Map<String, Object> m = (Map<String, Object>) array.get(i);
														
								int key=Integer.valueOf(String.valueOf(m.get(po_key)));
								if(key==point.getPointTime().intValue())
								{
									m.put("V",point.getPointValueInDouble());
									state++;
								}
							
							}
							
							if(state==0)
							{
								Map<String, Object> m =new HashMap<String, Object>();
								m.put("V",point.getPointValueInDouble() );
								m.put("S",point.getPointTime().intValue() );
								
								array.add(m);
							}
			
						jedis.hset(String.valueOf(rmc.getUkey()),"1", JSON.toJSONString(array));
						
						jedis.close();
					}

				} else  {

					
				} 

			}

			
			// mongoClient.close();
		}

	}

	

	
}
