package com.nms.server.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.nms.server.bean.EventRecordLibrary;
import com.nms.server.bean.ServerIpSegment;
import com.nms.server.bean.ServerTable;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;

/**
 *  <p>变更操作</p>
 *  <p>针对操作变更未及时下发到指定Client，而进行的后续操作</p>
 *  @date Mar 6, 2012 8:33:40 AM
 *	@author ZhangGang
 *
 */
public class ChangeService extends CommonService{
	private Logger logger = Logger.getLogger(ChangeService.class);
	public ChangeService(CommonDao dao){
		super(dao);
	}
	
	public List<EventRecordLibrary> getNewEventRecordList() {
		SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
		List<EventRecordLibrary>  erlList = new LinkedList<EventRecordLibrary>();

		StringBuffer sql = new StringBuffer();
		sql.append("select ");
		sql.append("erl.id, ");
		sql.append("erl.record_type, ");
		sql.append("erl.record_content, ");
		sql.append("erl.seq_ids, ");
		sql.append("erl.record_command, ");
		sql.append("to_char(erl.create_time,'"+Constants.DB_DATE_FORMAT+"') create_time, ");
		sql.append("erl.state ");
		sql.append("from event_record_library erl ");
		sql.append("where erl.state = 1 ");
		sql.append("and erl.NMSSERVER_ID = "+Common.getServerTable().getId());
		sql.append(" order by erl.create_time asc");
		
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("state");
		fields.add("record_type");
		fields.add("record_command");
		fields.add("record_content");
		fields.add("seq_ids");
		fields.add("create_time");

		try {
			List<Map<String, String>> maps = dao.dbSelect(sql.toString(), fields);
			if (maps!=null &&  maps.size()>0) {
				for (Map<String, String> map : maps) {
					EventRecordLibrary erl = new EventRecordLibrary();
					erl.setId(StringUtils.isEmpty(map.get("id"))?null:Long.parseLong(map.get("id")));
					erl.setState(StringUtils.isEmpty(map.get("state"))?null:Long.parseLong(map.get("state")));
					erl.setRecordType(map.get("record_type"));
					erl.setRecordCommand(map.get("record_command"));
					erl.setRecordContent(map.get("record_content"));
					erl.setSeqId(StringUtils.isEmpty(map.get("seq_ids"))?null:Long.parseLong(map.get("seq_ids")));
					erl.setCreateTime(StringUtils.isEmpty(map.get("create_time"))?null:format.parse(map.get("create_time")));
					erlList.add(erl);
				}
			}
		} catch (Exception e) {
			logger.error("EventRecordLibrary encapsulates ERROR",e);
		}finally{
			dao.clearConn();
		}
		return erlList;
	}
	
	public void saveEventRecordLibrary(String cmd,String seq_id,String type, String content) {
		SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
		try {
			Map<String, String> library = new HashMap<String, String>();
			library.put("record_command", cmd);
			library.put("record_content", content);
			library.put("record_type", type);
			library.put("seq_ids", seq_id);
			library.put("state", "1");
			library.put("NMSSERVER_ID", ""+Common.getServerTable().getId());
			library.put("create_time", format.format(System.currentTimeMillis()));
//			System.out.println("record_command"+ cmd);
//			System.out.println("record_content"+ content);
//			System.out.println("record_type"+  type);
//			System.out.println("seq_ids"+  seq_id);
//			System.out.println("state"+  "1");
//			System.out.println("NMSSERVER_ID"+  ""+Common.getServerTable().getId());
//			System.out.println("create_time"+  format.format(System.currentTimeMillis()));
			dao.insertObj("event_record_library",library);
		} catch (Exception e) {
			logger.error("Change record save failure", e);
		}finally{
			dao.clearConn();
		}
	}
	

	
	public void updateEventRecordLibrary(EventRecordLibrary event,String createTime,String content) {
		if(event.getId() == null){
			return ;
		}
		String sql = "update event_record_library erl set RECORD_CONTENT='"+content+"' ,CREATE_TIME=to_date('"+createTime+"','yyyy-MM-dd HH24:mi:ss' ) where id="+event.getId();
		try {
			dao.dbUpdate(sql);
		} catch (Exception e) {
			logger.error("Update the event_record_library exception: Record ID="+event.getId(),e);
		}finally{
			dao.clearConn();
		}
	}
	
	public void deleteEventRecordBySeqId(Long id) {
		if(id == null ){
			return ;
		}
		String sql = "delete from event_record_library  where lower(RECORD_TYPE)=lower('S2C') and  SEQ_IDS = '"+id.longValue()+"'";
		try {
			dao.dbUpdate(sql);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	public void deleteEventRecordByIds(String ids) {
		if(StringUtils.isEmpty(ids)){
			return ;
		}
		String sql = "delete from event_record_library  where id in ("+ids+")";
		try {
			dao.dbUpdate(sql);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	public void deleteEventRecordOldInfo() {
//		String sql = "delete event_record_library t where sysdate - t.create_time > 4";
		String sql = "delete from event_record_library  where create_time < sysdate-4 ";
		try {
			dao.dbUpdate(sql);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	
	public EventRecordLibrary selectEventRecordInfo(String recordType,String recordCommand,String seqId) {
		EventRecordLibrary event = null;
		try {
			if(StringUtils.isBlank(seqId)) {
				return event;
			}
			ArrayList<Map<String,String>> mapList = null;
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.clear();
			fields.add("id");
			fields.add("RECORD_TYPE");
			fields.add("RECORD_CONTENT");
			fields.add("SEQ_IDS");
			fields.add("RECORD_COMMAND");
			fields.add("CREATE_TIME");
			fields.add("NMSSERVER_ID");
			
			mapList = dao.dbSelect(" select ID,RECORD_TYPE,RECORD_CONTENT,SEQ_IDS,RECORD_COMMAND,CREATE_TIME,NMSSERVER_ID  " +
					" from  event_record_library erl " +
					" where erl.RECORD_TYPE='"+recordType+"' and erl.RECORD_COMMAND='"+recordCommand+"' and erl.SEQ_IDS=" + Long.parseLong(seqId.trim()) +
					" order by erl.CREATE_TIME desc",fields);
			
			if(mapList!=null && mapList.size()>0){
				Map<String,String> map  = mapList.get(0);
				if(StringUtils.isNotBlank(map.get("id")) ) {
					event =  new EventRecordLibrary();
					event.setId(Long.valueOf(map.get("id")));
					event.setRecordType(map.get("RECORD_TYPE"));
					event.setRecordContent(map.get("RECORD_CONTENT"));
					event.setSeqId(StringUtils.isBlank(map.get("SEQ_IDS"))? null:Long.valueOf(map.get("SEQ_IDS")));
					event.setRecordCommand(map.get("RECORD_COMMAND"));
				}
			}
		} catch (Exception e1) {
			logger.error("Query the event_record_library table exception",e1);
		}finally{
			dao.clearConn();
		}
		return event;
	}
	/*public static void main(String [] args) {
		CommonDao dao = null;
		ChangeService service = null;
		try {
			dao = new CommonDao();
			service = new ChangeService(new CommonDao());
			Common.setServerTable(service.getNMSServerParams("10.0.6.242"));
			List<EventRecordLibrary> list = service.getNewEventRecordList();
			for (int i = 0; i < list.size(); i++) {
				EventRecordLibrary library = list.get(i);
				pl(library.getId()+" "+library.getSeqId()+" "+library.getRecordType()+" "+library.getState());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(dao!=null)dao.close();
		}
		
		
	}*/
	
	public ServerTable getNMSServerParams(String ip) throws Exception{
		ServerTable serverTable = null;
		try {
			//查询server 信息
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("id");
			fields.add("server_name");
			fields.add("server_state");
			fields.add("server_ip");
			fields.add("server_ipn");
			ArrayList<Map<String, String>> mapsList = dao.dbSelect("select st.id,st.server_name,st.server_state, st.server_ip,st.server_ipn from server_table st where st.server_ip='" + ip + "'", fields);
//			pl(""+mapsList.size());
			if(mapsList!=null && mapsList.size()>0){
				serverTable = new ServerTable();
				Map<String, String> map = mapsList.get(0);
				serverTable.setId(StringUtils.isEmpty(map.get(fields.get(0))) ? null :  Long.parseLong(map.get(fields.get(0))));
				serverTable.setServerName(StringUtils.isEmpty(map.get(fields.get(1))) ? null : map.get(fields.get(1)));
				serverTable.setServerState(StringUtils.isEmpty(map.get(fields.get(2))) ? null : Long.parseLong(map.get(fields.get(2))));
				serverTable.setServerIp(StringUtils.isEmpty(map.get(fields.get(3))) ? null : map.get(fields.get(3)));
				serverTable.setServerIpn(StringUtils.isEmpty(map.get(fields.get(4))) ? null :  Long.parseLong(map.get(fields.get(4))));
			}else{
//				throw new Exception("IP为 "+ip+" 的DataController信息 数据库中不存在，请检查网络设置或进行人工DataController配置");
				throw new Exception("IP does not exist in the DataController information database for "+ip+" Check the network settings or manual DataController configuration");
			}
			
			//查询server 的管理IP段信息
			if(serverTable!= null && serverTable.getId()!=null){
				serverTable.setIpSegList(new LinkedList<ServerIpSegment>());
				fields.clear();
				fields.add("start_ip");
				fields.add("start_ipn");
				fields.add("end_ip");
				fields.add("end_ipn");
				mapsList = dao.dbSelect("select sis.start_ip,sis.start_ipn,sis.end_ip,sis.end_ipn from server_ip_segment sis where sis.server_id='" + serverTable.getId().longValue() + "'", fields);
//				pl(""+mapsList.size());
				if(mapsList!=null && mapsList.size()>0){
					for(Map<String, String> map : mapsList){
						ServerIpSegment segment = new ServerIpSegment();
						segment.setStartIp(StringUtils.isEmpty(map.get(fields.get(0))) ? null : map.get(fields.get(0)));
						segment.setStartIpn(StringUtils.isEmpty(map.get(fields.get(1))) ? null :  Long.parseLong(map.get(fields.get(1))));
						segment.setEndIp(StringUtils.isEmpty(map.get(fields.get(2))) ? null : map.get(fields.get(2)));
						segment.setEndIpn(StringUtils.isEmpty(map.get(fields.get(3))) ? null :  Long.parseLong(map.get(fields.get(3))));
						serverTable.getIpSegList().add(segment);
					}
				}else{
//					throw new Exception("IP为 "+ip+" 的DataController的IP段信息 数据库中不存在 请进行人工配置");
					throw new Exception("IP does not exist in the  "+ip+" segment information database of DataController for IP. Please configure manually");
				}
			}else{
//				throw new Exception("IP为 "+ip+" 的DataController信息 查询异常 无法查询出ID");
				throw new Exception("DataController information with IP "+ip+" query exception Unable to query ID");
			}
		} catch (Exception e) {
			logger.error("By parameter："+ ip+" to get node information failure",e);
		}finally{
			dao.clearConn();
		}
		return serverTable;
		
	}

}
