package flow;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
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月20日 下午05时48分09秒
 */
public class GetStrategyID extends com.avaya.sce.runtime.BasicServlet {
	private static Logger log = Logger.getLogger(GetStrategyID.class);
	//{{START:CLASS:FIELDS
	//}}END:CLASS:FIELDS

	/**
	 * Default constructor
	 * Last generated by Orchestration Designer at: 2021年7月20日 下午05时48分09秒
	 */
	public GetStrategyID() {
		//{{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年7月20日 下午05时48分09秒
	 */
	
	public void servletImplementation(com.avaya.sce.runtimecommon.SCESession mySession) {
		String strategyList = mySession.getVariableField(IProjectVariables.STRATEGY_LIST).getStringValue();
		if(strategyList.equals("0")){
			strategyList(mySession);
			setStrategy(mySession);
		}else {
			setStrategy(mySession);
		}
		String menuID = mySession.getVariableField(IProjectVariables.STRATEGY_ID).getStringValue();
		String type = mySession.getVariableField(IProjectVariables.SMSSTRATEGY,IProjectVariables.SMSSTRATEGY_FIELD_TYPE).getStringValue();
		
		if((menuID.equals("welcome_pt")||menuID.equals("welcome_vip"))&&(type.equals("1")||type.equals("3"))){
			String node_id=null;
			String end_reason=null;
			if(menuID.equals("welcome_pt")){
				node_id="busy_pt";
				end_reason="前置繁忙_普通";
			}else {
				node_id="busy_vip";
				end_reason="前置繁忙_VIP";
			}
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			
		}
	}
	/**
	 * 利用strategyList获取数据库中的策略位集合
	 * @ClassName:GetStrategyID 
	 * @Description:获取IVRMenuConfig表中条件是region对应流程的策略位
	 * @author:seven
	 * @date:2021年2月15日 
	 *  
	 */
	public void strategyList(com.avaya.sce.runtimecommon.SCESession mySession){
			 Properties properties = new Properties();
			 SimpleDateFormat df2 = new SimpleDateFormat("HH:mm:ss");
			 String time = df2.format(new Date());
				ResultSet rs=null;
				Connection conn = null;
				PreparedStatement pre =null;
				try {
					String type = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_TYPE).getStringValue();
					String driver = null;
					String user = null;
					String password = null;
					String url = null;
					// 若安装多个实例时，要确认相应的port及实例名
					if(type.equals("0")){
						log.debug("-----当前数据库为测试库-----");
						driver = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_DRIVER_2).getStringValue();
						Class.forName(driver);
						user = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_USER_2).getStringValue();
						password = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_PASSWORD_2).getStringValue();
						url = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_URL_2).getStringValue();
					}else {
						log.debug("-----当前数据库为正式库-----");
						driver = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_DRIVER_1).getStringValue();
						Class.forName(driver);
						user = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_USER_1).getStringValue();
						password = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_PASSWORD_1).getStringValue();
						url = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_URL_1).getStringValue();
					}
					
					System.out.println(url + "+url+" + user + "+username+"
							+ password + "+password+" + driver + "+driver");

					conn = null;
					Class.forName(driver);
					//System.out.println(mySession.getVariableField("创建数据库连接成功");
					log.info("-----GetStrategyID-----   "+"创建数据库连接成功");
					DriverManager.setLoginTimeout(2);
					conn = DriverManager.getConnection(url, user, password);
					log.info("-----GetStrategyID-----   "+"创建数据库连接成功----并成功登入登入账户为"+user);
					String tab = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_TABLE_4).getStringValue();
					String condition = mySession.getVariableField(IProjectVariables.DB,IProjectVariables.DB_FIELD_TABLE_4CONDITION).getStringValue();
					String sql ="SELECT * from "+tab+" where region='"+condition+"' and deleted=0 and workbegintime<'"+time+"'"+" and workendtime>'"+ time+"'";
					log.info("-----GetStrategyID-----   "+"运行的sql语句是："+sql);
					
					pre = conn.prepareStatement(sql);
		            rs=pre.executeQuery();
		            Object RSO =new Strategy();
		            HashMap<String,Strategy> sls=new HashMap<String,Strategy>();
		            //log.info("-----GetMenuID-----  "+"每一条回传的内容：  "+ rs.toString());
		            while(rs.next()){
		            	Strategy strategy = new Strategy();
		            	strategy.setId(rs.getString("menuid"));
		            	strategy.setType(rs.getString("playtype"));
		            	strategy.setSMStxt(rs.getString("smstext"));
		            	strategy.setPortals(rs.getString("playtext"));
		            	sls.put(strategy.getId(), strategy);
		            	//log.info("-----GetMenuID-----  "+"每一条回传的内容：  "+ strategy.toString());
		            }
		            mySession.getVariableField(IProjectVariables.STRATEGY_LIST).setValue(sls);
		            log.info("-----GetStrategyID-----  "+"所有内容：  "+ sls.toString());
				}catch (Exception e) {
					log.info("-----GetStrategyID-----  数据库连接失败，失败代码是："+e.getMessage());
				}
		
		}
	/**
	 * 遍历该变量中存入的集合，将对应的menuID参数  赋予strategy集合变量中；
	 * @ClassName:GetStrategyID 
	 * @Description:将STRATEGY_LIST变量中的Strategy类集合解析，并对应STRATEGY_ID对应的Strategy类赋予各个对应变量
	 * @author:seven
	 * @date:2021年2月15日 
	 *  
	 */
	public void setStrategy(com.avaya.sce.runtimecommon.SCESession mySession){
			
			String menuID = mySession.getVariableField(IProjectVariables.STRATEGY_ID).getStringValue();
			//log.info("-----GetStrategyID-----  menuID："+menuID);
			//log.info("-----GetStrategyID-----  STRATEGY_LIST："+sls.size());
			try {
				HashMap<String,Strategy> sls  = (HashMap<String, Strategy>) mySession.getVariableField(IProjectVariables.STRATEGY_LIST).getObjectValue();
				Strategy strategy = sls.get(menuID);
				//log.info("-----GetStrategyID-----  strategy:"+strategy.toString());
				sls.get(menuID).toString();
				//log.info("-----GetStrategyID-----  sls.get(menuID).toString():"+sls.get(menuID).toString());
				String id = sls.get(menuID).getId();
				//log.info("-----GetStrategyID-----  id："+id);
				String portals = sls.get(menuID).getPortals();
				//log.info("-----GetStrategyID-----  portals："+portals);
				String smstxt = sls.get(menuID).getSMStxt();
				//log.info("-----GetStrategyID-----  smstxt："+smstxt);
				String type = sls.get(menuID).getType();
				//log.info("-----GetStrategyID-----  type："+type);
				log.info("-----GetStrategyID-----  从集合中获取到的参数是："+sls.get(menuID).toString());
				mySession.getVariableField(IProjectVariables.SMSSTRATEGY,IProjectVariables.SMSSTRATEGY_FIELD_ID).setValue(id);
				//log.info("-----GetStrategyID-----  从集合中获取到的参数是："+sls.get(menuID).toString());
				
				mySession.getVariableField(IProjectVariables.SMSSTRATEGY,IProjectVariables.SMSSTRATEGY_FIELD_PORTALS).setValue(portals);
				
				mySession.getVariableField(IProjectVariables.SMSSTRATEGY,IProjectVariables.SMSSTRATEGY_FIELD_SMSTXT).setValue(smstxt);
				//当前策略位状态类型
				mySession.getVariableField(IProjectVariables.SMSSTRATEGY,IProjectVariables.SMSSTRATEGY_FIELD_TYPE).setValue(type);
				//当前策略位短信编码
				mySession.getVariableField(IProjectVariables.DXBM).setValue(smstxt);
			} catch (Exception e) {
				log.info("-----GetStrategyID-----  从集合中获参数出现错误："+e.getMessage());
				mySession.getVariableField(IProjectVariables.SMSSTRATEGY,IProjectVariables.SMSSTRATEGY_FIELD_TYPE).setValue(0);
			}
			
		}
	
	/**
	 * 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分31秒
	 */
	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("GetStrategyIDType", 0, true, "Default");
		list.add(aGoto);

		return list;
	}
}
