package flow;

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

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年5月25日 上午08时56分48秒
 */
public class ser_getMenuResult extends com.avaya.sce.runtime.BasicServlet {
	private static Logger log = Logger.getLogger(ser_getMenuResult.class);
	// {{START:CLASS:FIELDS
	// }}END:CLASS:FIELDS

	/**
	 * Default constructor Last generated by Orchestration Designer at:
	 * 2021年5月25日 上午08时56分48秒
	 */
	public ser_getMenuResult() {
		// {{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 timeout, the platform may
	 * throw an "error.badfetch".
	 * 
	 * 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年5月25日 上午08时56分48秒
	 */
	public void servletImplementation(
			com.avaya.sce.runtimecommon.SCESession mySession) {
		System.out.println("进入ser_getMenuResult");
		String NextNodeID = mySession.getVariableField(
				IProjectVariables.NEXT_MENU).getStringValue();
		String next_node = "end";
		//String next_node = "ser_NodeSQL";
		String ResultDTMF = mySession.getVariableField(
				IProjectVariables.MENU_1,
				IProjectVariables.COLLECT_FIELD_UTTERANCE).getStringValue();

		HashMap<Integer, Object> hMapAll = (HashMap<Integer, Object>) mySession
				.getVariableField(IProjectVariables.MENU_ALL).getObjectValue();
		HashMap<Integer, ArrayList<CMenuItemConfig>> hMapChild = (HashMap<Integer, ArrayList<CMenuItemConfig>>) mySession
				.getVariableField(IProjectVariables.MENU_CHILD)
				.getObjectValue();
		HashMap<Integer, CMenuConfig> hMapParent = (HashMap<Integer, CMenuConfig>) mySession
				.getVariableField(IProjectVariables.MENU_PARENT)
				.getObjectValue();

		int nomatchcount = mySession.getVariableField(IProjectVariables.MENU_1,
				IProjectVariables.MENU_1_FIELD_NOMATCHCOUNT).getIntValue();
		int noinput = mySession.getVariableField(IProjectVariables.MENU_1,
				IProjectVariables.MENU_1_FIELD_NOINPUTCOUNT).getIntValue();
		int menuErrorCount = mySession.getVariableField(
				IProjectVariables.MENU_ERROR_COUNT).getIntValue();
		System.out.println("noinput:"+noinput+"    nomatchcount:"+nomatchcount+" menuErrorCount:"+menuErrorCount);
		if (nomatchcount + noinput > 0) {
			//是否记录ALLKEY数据状态 type ：N（不记录）；Y（记录）；
			String type="N";
			menuErrorCount++;
			mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT).setValue(noinput);
			mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH).setValue(nomatchcount);
					
			/*String nodeRecord = mySession.getVariableField(IProjectVariables.NODE_RECORD).getStringValue();
			if(!nodeRecord.equals("0")){
				IVR_NodeRecord smNodeRecord = (IVR_NodeRecord)mySession.getVariableField(IProjectVariables.NODE_RECORD).getObjectValue();
				//给当前节点用户未按键数量赋值
				if(noinput>0){
					int inputCount = mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT_COUNT).getIntValue();
					inputCount=inputCount+1;
					mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT_COUNT).setValue(inputCount);
				}
				//给当前节点用户按错数量赋值
				if(nomatchcount>0){
					int matchCount = mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH_COUNT).getIntValue();
					matchCount=matchCount+1;
					mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH_COUNT).setValue(matchCount);
				}
			} */
			//IVR_NodeRecord smNodeRecord = (IVR_NodeRecord)mySession.getVariableField(IProjectVariables.NODE_RECORD).getObjectValue();
			//给当前节点用户未按键数量赋值
			if(noinput>0){
				int inputCount = mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT_COUNT).getIntValue();
				inputCount=inputCount+1;
				mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT_COUNT).setValue(inputCount);
			}
			//给当前节点用户按错数量赋值
			if(nomatchcount>0){
				int matchCount = mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH_COUNT).getIntValue();
				matchCount=matchCount+1;
				mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH_COUNT).setValue(matchCount);
			}
			if(hMapParent.containsKey(NextNodeID)){
				CMenuConfig CMenuConfig	=hMapParent.get(NextNodeID);
				int maxerrorcount=CMenuConfig.getMenuErrorMaxCount();
				System.out.println("读取到最大错误次数:"+maxerrorcount);
				if(maxerrorcount<=menuErrorCount)
				{
					//给当前节点是否正确输入赋值
					/*if(!nodeRecord.equals("0")){
						mySession.getVariableField(IProjectVariables.MENU_INPUT_YOR_N).setValue("0");
					}*/
					System.out.println("挂机，错误次数超过最大尝试:"+maxerrorcount);
					mySession.getVariableField(IProjectVariables.MENU_ERROR_COUNT).setValue(maxerrorcount);
					mySession.getVariableField(IProjectVariables.NEXT_MENU).setValue("S500");
					//获取系统存入的节点信息
					/*String nodeRecordError = mySession.getVariableField(IProjectVariables.NODE_RECORD).getStringValue();
					if(!nodeRecordError.equals("0")){
						andNedeList(mySession,type);
						
					}*/
				}
				else
				{
					System.out.println("设置最大尝试:"+menuErrorCount);
					mySession.getVariableField(
							IProjectVariables.MENU_ERROR_COUNT).setValue(menuErrorCount);
				}
			}
		} else {
			//是否记录ALLKEY数据状态 type ：N（不记录）；Y（记录）；
			String type="Y";
			System.out.println("清空最大尝试次数");
			/*mySession.getVariableField(
					IProjectVariables.MENU_ERROR_COUNT).setValue(0);*/
			if (hMapChild.containsKey(NextNodeID)) {
				mySession.getVariableField(IProjectVariables.MENU_CHILD)
						.getObjectValue();
				ArrayList<CMenuItemConfig> list = hMapChild.get(NextNodeID);
				for (CMenuItemConfig cMenuItemConfig : list) {

					if (cMenuItemConfig.getDTMF().equals(ResultDTMF)) {
						//获取系统存入的节点信息
						/*String nodeRecord = mySession.getVariableField(IProjectVariables.NODE_RECORD).getStringValue();
						//判断主菜单是否记录
						if(!nodeRecord.equals("0")){
							andNedeList(mySession,type);
						}
						//判断主子节点是否记录
						if(cMenuItemConfig.getSonNodeType().equals("ON")&&!nodeRecord.equals("0")){
							andSonNedeList(mySession,cMenuItemConfig);
						}*/
						mySession.getVariableField(IProjectVariables.MENU_ERROR_COUNT).setValue(0);
						mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH_COUNT).setValue(0);
						mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT_COUNT).setValue(0);
						mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH).setValue(0);
						mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT).setValue(0);
						cMenuItemConfig.getSonNodeType();
						String NextID = cMenuItemConfig.getNextMenu();
						String ItemMenuName = cMenuItemConfig.getItemMenuName();
						if (!ItemMenuName.equals("")) {
							mySession.getVariableField(
									IProjectVariables.CURRENT_MENU_NAME)
									.setValue(ItemMenuName);
							System.out
									.println("ser_getMenuResult,设置CURRENT_MENU_NAME="
											+ ItemMenuName);
						}
						System.out.println("ser_getMenuResult,设置Next_Menu="
								+ cMenuItemConfig);
						String transferno = cMenuItemConfig.getTransferNO();
						if(!transferno.isEmpty()||transferno!=null){
							mySession.getVariableField(IProjectVariables.SL_SERV_NAME).setValue(cMenuItemConfig.getRemark());
							mySession.getVariableField(IProjectVariables.SL_CALL_IN_TYPE).setValue("1020");
							mySession.getVariableField(IProjectVariables.TRANS_DNIS).setValue(transferno);
							System.out.println("ser_getMenuResult,设置TRANS_DNIS="+ transferno);
						}
						String smstemplate = cMenuItemConfig.getSMSTemplate();
						if (smstemplate != null && !smstemplate.equals("")) {
							mySession.getVariableField(IProjectVariables.SMSTEMPLATE_ID).setValue(smstemplate);
							System.out.println("ser_getMenuResult,设置SMSTemplate="+ smstemplate);
						}
						mySession.getVariableField(IProjectVariables.NEXT_MENU)
								.setValue(NextID);
					}

				}
			}
		}

	}
	/**
	 * 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 type){
		String nodeRecord = mySession.getVariableField(IProjectVariables.NODE_RECORD).getStringValue();
		try {
			
			//nodeRecord变量为0时 证明该节点不需要记录， 直接跳过子流程判断
			if(!nodeRecord.equals("0")){
				//创建节点记录类
				IVR_NodeRecord ivrnr = new IVR_NodeRecord();
				//获取nodeRecord当前节点
				IVR_NodeRecord smsnr = (IVR_NodeRecord)mySession.getVariableField(IProjectVariables.NODE_RECORD).getObjectValue();
				//给当前节点是否点击返回上一层赋予初始值
				ivrnr.setUpperStoryYorN(0);
				//给当前节点是否点击重听赋予初始值
				ivrnr.setRepeatYornYorN(0);
				//给 整通通话的按键记录  全部按键记录 赋值
				String allKey = mySession.getVariableField(IProjectVariables.NODE_RECORD_ALL_KEY).getStringValue();
				if(type.equals("Y")){
					String menuValue = mySession.getVariableField(IProjectVariables.MENU_1,IProjectVariables.MENU_1_FIELD_UTTERANCE).getStringValue();
					//String menuValue2 = mySession.getVariableField(IProjectVariables.MENU_1,IProjectVariables.MENU_1_FIELD_VALUE).getStringValue();
					if(allKey.isEmpty()){
						mySession.getVariableField(IProjectVariables.NODE_RECORD_ALL_KEY).setValue(menuValue);
					}else {
						allKey=allKey+menuValue;
						mySession.getVariableField(IProjectVariables.NODE_RECORD_ALL_KEY).setValue(allKey);
					}
					
					if(menuValue.equals("#")){
						//给当前节点是否点击重听赋值
						ivrnr.setRepeatYornYorN(1);
					}
					if(menuValue.equals("*")){
						//给当前节点是否点击重听赋值
						ivrnr.setUpperStoryYorN(1);
					}
				}
				
				//节点开始时间
				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.setTransferYorN(0); 
				//给当前节点是否正确输入赋值
				ivrnr.setInputYorN(mySession.getVariableField(IProjectVariables.MENU_INPUT_YOR_N).getIntValue()); 
				//给当前节点用户未按键数量赋值
				ivrnr.setNoInputCount(mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT_COUNT).getIntValue());
				//给当前节点用户按错数量赋值
				ivrnr.setNoMatchCount(mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH_COUNT).getIntValue());
				//主菜单记录
				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){
						String menuID = nr.getcMenuConfig().getMenuID();
						String menuID2 = ivrnr.getcMenuConfig().getMenuID();
						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("-----菜单节点的NedeList时间剪辑出现错误： "+e.getMessage()+"-----");
				}
				mySession.getVariableField(IProjectVariables.NODE_RECORD).setValue("0");
				
				//将当前节点添加到 系统节点记录集合中
				ivrNRL.add(ivrnr);
				//重置菜单节点数据
				mySession.getVariableField(IProjectVariables.MENU_INPUT_YOR_N).setValue(1); 
				mySession.getVariableField(IProjectVariables.MENU_ERROR_INPUT_COUNT).setValue(0);
				mySession.getVariableField(IProjectVariables.MENU_ERROR_MATCH_COUNT).setValue(0);
			}
		} 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("menuError", 0, true, "Default");
		list.add(aGoto);

		return list;
	}
}
