package flow;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * A basic servlet which allows a user to define their code, generate
 * any output, and to select where to transition to next.
 * Last generated by Orchestration Designer at: 2021年7月6日 下午05时08分04秒
 */
public class ser_checkannNext extends com.avaya.sce.runtime.BasicServlet {
	private static Logger log = Logger.getLogger(ser_checkannNext.class);
	//{{START:CLASS:FIELDS
	//}}END:CLASS:FIELDS

	/**
	 * Default constructor
	 * Last generated by Orchestration Designer at: 2021年7月6日 下午05时08分04秒
	 */
	public ser_checkannNext() {
		//{{START:CLASS:CONSTRUCTOR
		super();
		//}}END:CLASS:CONSTRUCTOR
	}

	/**
	 * This method allows for custom integration with other Java components.
	 * You may use Java for sophisticated logic or to integrate with custom
	 * connectors (i.e. JMS, custom web services, sockets, XML, JAXB, etc.)
	 *
	 * Any custom code added here should work as efficiently as possible to prevent delays.
	 * It's important to design your callflow so that the voice browser (Voice Portal/IR)
	 * is not waiting too long for a response as this can lead to a poor caller experience.
	 * Additionally, if the response to the client voice browser exceeds the configured
	 *
	 * Using this method, you have access to all session variables through the 
	 * SCESession object.
	 *
	 * The code generator will *** NOT *** overwrite this method in the future.
	 * Last generated by Orchestration Designer at: 2021年7月6日 下午05时08分04秒
	 */
	public void servletImplementation(com.avaya.sce.runtimecommon.SCESession mySession) {
		
		String NextNodeID = mySession.getVariableField(IProjectVariables.NEXT_MENU).getStringValue();
		String next_node = "end";
		//String next_node = "ser_NodeSQL";
		System.out.println("NextNodeID:"+NextNodeID);
		String Result=mySession.getVariableField(IProjectVariables.SER_RESULT).getStringValue();
		System.out.println("Result:"+Result);
		HashMap<String, Object>  hMapAll = (HashMap<String, Object>) mySession
				.getVariableField(IProjectVariables.MENU_ALL)
				.getObjectValue();
		HashMap<String, ArrayList<CMenuItemConfig>> hMapChild = (HashMap<String, ArrayList<CMenuItemConfig>>) mySession
				.getVariableField(IProjectVariables.MENU_CHILD)
				.getObjectValue();
		HashMap<String, CMenuConfig> hMapParent = (HashMap<String, CMenuConfig>) mySession
				.getVariableField(IProjectVariables.MENU_PARENT)
				.getObjectValue();
		
		if (hMapAll.containsKey(NextNodeID)) {
			CMenuConfig CMenuConfig = (CMenuConfig) hMapAll.get(NextNodeID);
			System.out.println("setannnext:"+CMenuConfig);
			mySession.getVariableField(IProjectVariables.NEXT_MENU).setValue(CMenuConfig.getNextMenu());
		}
		//添加基础节点
		andNedeList(mySession);
		//添加子类节点
		if (hMapChild.containsKey(NextNodeID)) {
			ArrayList<CMenuItemConfig> list = hMapChild.get(NextNodeID);
			for (CMenuItemConfig cmc : list) {
				if(cmc.getSonNodeType().equals("ON")){
					andSonNedeList(mySession,cmc);
				}
			}
		}
		
		
		
		
	}
	/**
	 * andNedeList方法主要是判断变量 nodeRecord （当前节点） 是否需要添加到 nodeRecordList （所有节点集合）并将，nodeRecordOrder（节点数序）赋值
	 * @ClassName: ser_checkannNext 
	 * @Description: seven
	 * @author 根据数据库主表节点记录开关，表节点记录开关 同时开启时记录该节点 同时重置nodeRecord（当前节点）节点值给0
	 * @date 2022年2月17日 下午4：55
	 *  
	 */
	public void andNedeList(com.avaya.sce.runtimecommon.SCESession mySession){
		String nodeRecord = mySession.getVariableField(IProjectVariables.NODE_RECORD).getStringValue();
		try {
			//nodeRecord变量为0时 证明该节点不需要记录， 直接跳过子流程判断
			if(!nodeRecord.equals("0")){
				//获取nodeRecord当前节点
				IVR_NodeRecord smsnr = (IVR_NodeRecord)mySession.getVariableField(IProjectVariables.NODE_RECORD).getObjectValue();
				
				//创建节点记录类
				IVR_NodeRecord ivrnr = new IVR_NodeRecord();
				//节点开始时间
				ivrnr.setNodeBeginTime(smsnr.getNodeBeginTime());
				//获取系统nodeRecordOrder节点顺序
				int nrOrder = mySession.getVariableField(IProjectVariables.NODE_RECORD_ORDER).getIntValue();
				//给当前节点序列赋值
				nrOrder=nrOrder+1;
				ivrnr.setNodeOrder(nrOrder);
				//更改系统nodeRecordOrder节点顺序
				mySession.getVariableField(IProjectVariables.NODE_RECORD_ORDER).setValue(nrOrder);
				//给当前节点是否点击返回上一层赋值
				ivrnr.setUpperStoryYorN(2);
				//给当前节点是否点击重听赋值
				ivrnr.setRepeatYornYorN(2);
				//给当前节点是否正确输入赋值
				ivrnr.setInputYorN(2); 
				//给当前节点是否点击转人工赋值
				ivrnr.setTransferYorN(2); 
				//给当前节点用户未按键数量赋值
				ivrnr.setNoInputCount(0);
				//给当前节点用户按错数量赋值
				ivrnr.setNoMatchCount(0);
				//主菜单记录
				ivrnr.setcMenuConfig(smsnr.getcMenuConfig());
				//给当前节点是否为第一次进入 先赋予1 ， 在检测nodeRecordList 节点集合中是否有重复出现， 若重复出现变更为0
				ivrnr.setFirstEntryYorN(1);
				ArrayList<IVR_NodeRecord> ivrNRL=(ArrayList<IVR_NodeRecord>)mySession.getVariableField(IProjectVariables.NODE_RECORD_LIST).getObjectValue();
				if(ivrNRL.size()>0){
					for(IVR_NodeRecord nr:ivrNRL){
						if (nr.getcMenuConfig().getMenuID().equals(ivrnr.getcMenuConfig().getMenuID())) {
							ivrnr.setFirstEntryYorN(0);
							break;
						}
					}
				}
				//给当前节点结束时间赋值
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
				String nrEndTime = sdf.format(new Date());
				ivrnr.setNodeEndTime(nrEndTime);
				
				//给当前节点赋予整体运转时间
				long endTime;
		        long startTime;
		        int npt=0;
				try {
					startTime =sdf.parse(smsnr.getNodeBeginTime()).getTime();
					endTime = sdf.parse(nrEndTime).getTime();
					long deff=(endTime-startTime);
					System.out.println("      "+deff);
					npt = new Long(deff).intValue();
					ivrnr.setNodeProcessingTime(npt);
				} catch (ParseException e) {
					log.debug("-----音频的时间剪辑出现错误： "+e.getMessage()+"-----");
				}
				mySession.getVariableField(IProjectVariables.NODE_RECORD).setValue("0");
				//将当前节点添加到 系统节点记录集合中
				ivrNRL.add(ivrnr);
				
			}
		} catch (Exception e) {
			log.debug("-----音频的andNedeList方法出现错误： "+e.getMessage()+"-----");
			e.printStackTrace();
		}
		
	}
	
	/**
	 * andSonNedeList方法主要是添加当前子表sonNodeType是否开启，若开启将当前子表属性添加到 nodeRecordList （所有节点集合）并将，nodeRecordOrder（节点数序）赋值
	 * @ClassName: ser_checkannNext 
	 * @Description: seven
	 * @author 根据数据库子表表节点记录开关，表节点记录开关 同时开启时记录该节点 
	 * @date 2022年3月1日 下午2：32
	 *  
	 */
	public void andSonNedeList(com.avaya.sce.runtimecommon.SCESession mySession,CMenuItemConfig cmic){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		try {
			//获取nodeRecord当前节点
			//创建节点记录类
			IVR_NodeRecord ivrnr = new IVR_NodeRecord();
			CMenuConfig menuConfig = new CMenuConfig();
			//给当前节点赋予名称
			System.out.println(cmic.getItemMenuName());
			menuConfig.setMenuName(cmic.getItemMenuName());
			//给当前节点赋予ID
			menuConfig.setMenuID(cmic.getMenuItemId());
			//将CMenuConfig 给IVR_NodeRecord
			ivrnr.setcMenuConfig(menuConfig);
			//节点开始时间
			String nrBGTime = sdf.format(new Date());
			ivrnr.setNodeBeginTime(nrBGTime);
			//获取系统nodeRecordOrder节点顺序
			int nrOrder = mySession.getVariableField(IProjectVariables.NODE_RECORD_ORDER).getIntValue();
			//给当前节点序列赋值
			nrOrder=nrOrder+1;
			ivrnr.setNodeOrder(nrOrder);
			//更改系统nodeRecordOrder节点顺序
			mySession.getVariableField(IProjectVariables.NODE_RECORD_ORDER).setValue(nrOrder);
			//给当前节点是否点击返回上一层赋值
			ivrnr.setUpperStoryYorN(2);
			//给当前节点是否点击重听赋值
			ivrnr.setRepeatYornYorN(2);
			//给当前节点是否正确输入赋值
			ivrnr.setInputYorN(2); 
			//给当前节点是否点击转人工赋值
			ivrnr.setTransferYorN(2); 
			//给当前节点用户未按键数量赋值
			ivrnr.setNoInputCount(0);
			//给当前节点用户按错数量赋值
			ivrnr.setNoMatchCount(0);
			//主菜单记录
			//ivrnr.setcMenuConfig(smsnr.getcMenuConfig());
			//给当前节点是否为第一次进入 先赋予1 ， 在检测nodeRecordList 节点集合中是否有重复出现， 若重复出现变更为0
			ivrnr.setFirstEntryYorN(1);
			ArrayList<IVR_NodeRecord> ivrNRL=(ArrayList<IVR_NodeRecord>)mySession.getVariableField(IProjectVariables.NODE_RECORD_LIST).getObjectValue();
			if(ivrNRL.size()>0){
				for(IVR_NodeRecord nr:ivrNRL){
					if (nr.getcMenuConfig().getMenuID().equals(ivrnr.getcMenuConfig().getMenuID())) {
						ivrnr.setFirstEntryYorN(0);
						break;
					}
				}
			}
			//给当前节点结束时间赋值
			String nrEndTime = sdf.format(new Date());
			ivrnr.setNodeEndTime(nrEndTime);
			
			//给当前节点赋予整体运转时间
			long endTime;
	        long startTime;
	        int npt=0;
			try {
				startTime =sdf.parse(nrBGTime).getTime();
				endTime = sdf.parse(nrEndTime).getTime();
				long deff=(endTime-startTime);
				System.out.println("      "+deff);
				npt = new Long(deff).intValue();
				ivrnr.setNodeProcessingTime(npt);
			} catch (ParseException e) {
				log.debug("-----andSonNedeList音频的时间剪辑出现错误： "+e.getMessage()+"-----");
			}
			mySession.getVariableField(IProjectVariables.NODE_RECORD).setValue("0");
			//将当前节点添加到 系统节点记录集合中
			ivrNRL.add(ivrnr);
			
		} catch (Exception e) {
			log.debug("-----音频的andSonNedeList方法出现错误： "+e.getMessage()+"-----");
			e.printStackTrace();
		}
		
	}
	/**
	 * Builds the list of branches that are defined for this servlet object.
	 * This list is built automatically by defining Goto nodes in the call flow editor.
	 * It is the programmer's responsibilty to provide at least one enabled Goto.<BR>
	 *
	 * The user should override updateBranches() to determine which Goto that the
	 * framework will activate.  If there is not at least one enabled Goto item, 
	 * the framework will throw a runtime exception.<BR>
	 *
	 * This method is generated automatically and changes to it may
	 * be overwritten next time code is generated.  To modify the list
	 * of branches for the flow item, override:
	 *     <code>updateBranches(Collection branches, SCESession mySession)</code>
	 *
	 * @return a Collection of <code>com.avaya.sce.runtime.Goto</code>
	 * objects that will be evaluated at runtime.  If there are no gotos
	 * defined in the Servlet node, then this returns null.
	 * Last generated by Orchestration Designer at: 2023年4月14日 下午05时14分30秒
	 */
	public java.util.Collection getBranches(com.avaya.sce.runtimecommon.SCESession mySession) {
		java.util.List list = null;
		com.avaya.sce.runtime.Goto aGoto = null;
		list = new java.util.ArrayList(1);

		aGoto = new com.avaya.sce.runtime.Goto("ser_setNext", 0, true, "Default");
		list.add(aGoto);

		return list;
	}
}
