package com.sino.publicclass.base;

import java.sql.Connection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sino.publicclass.common.HttpDataParser;
import com.sino.publicclass.database.ConnectionPool;
import com.sino.publicclass.util.StaticVar;

public abstract class BaseAction {
	public BaseAction() {
		log = LogFactory.getLog(getClass().getName());
	}

	private Log log = null;
	private String failureMsg = StaticVar.NO_MESSAGE;
	private String successMsg = StaticVar.NO_MESSAGE;
	private String nextPage = "no";
	private Connection conn = null;
	private boolean isConnection = false;
	private boolean isAutoCommit = false;
	private boolean isTransition = false;
	private boolean isRollback = false;
	private String cmd = "";
	private String transitionURI = null;
	private Memory memory = new Memory();
	public HttpServletRequest request;
	public HttpServletResponse response;
	private HttpSession session = null;
	private boolean isNext = true;

	/**
	 * service 方法注解。
	 */
	public void service(HttpServletRequest req, HttpServletResponse res) throws Exception {
		try {
			request = req;
			response = res;
		//	init();
			if (userVaildate(req,res)) {
				performTask();
			}
			if (isNext) {
				saveMemory();
				nextPage();
			}
		} catch (Exception exs) {
			this.isRollback = true;
			throw exs;
		} finally {
			try {
				closeConnection();
			} catch (Exception ex) {
				throw new CException("closeConnection() error");
			}
		}
		req.setAttribute("failureMsg", failureMsg);
		req.setAttribute("successMsg", successMsg);
	}

	/*public void init() throws CException {
		Enumeration names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			if (PageTools.validateMemory(name)) {
				this.memory.put(name, getParameter(name));
			}
		}
	}*/

	public void performTask() throws CException {
		String CMD = "";
		try {
			CMD = readCMD();
			log.info("method:" + CMD + "()");
			this.getClass().getMethod(CMD, null).invoke(this, null);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public String[] getParameterValues(String parameterName) {
		return request.getParameterValues(parameterName);
	}

	public String getParameter(String parameterName, String defaultValue) {
		String paramValue = getParameter(parameterName);
		// 假如无该变量参数，返回缺省值
		if (paramValue == null) {
			paramValue = defaultValue;
		}
		return paramValue.trim();
	}

	public String getParameter(String parameterName) {
		String paramValue = null;
		String[] parameterValues = getParameterValues(parameterName);
		if (parameterValues != null) {
			paramValue = parameterValues[0];
		}
		return paramValue;
	}

	public String getParameter(String parameterName, String defaultValue, boolean isMemory) {
		String value = getParameter(parameterName, defaultValue);
		if (isMemory) {
			setMemory(parameterName, value);
		} else {
			removeMemory(parameterName);
		}
		return value;
	}

	/**
	 * @param parameterName
	 *            String
	 * @param defaultValue
	 *            int 找不到parameterName，返回defaultValue
	 * @param defaultValue2
	 *            int 找到parameterName，但值为""，返回defaultValue2
	 * @return int
	 */
	public int getParameter(String parameterName, int defaultValue, int defaultValue2) throws CException {
		String paramValue = getParameter(parameterName, String.valueOf(defaultValue));
		int value = 0;
		if (paramValue.equals("")) {
			value = defaultValue2;
		} else {
			try {
				value = Integer.parseInt(paramValue);
			} catch (Exception ex) {
				throw new CException("[" + parameterName + "] isn't int type!");
			}
		}
		return value;
	}

	public int getParameter(String parameterName, int defaultValue, int defaultValue2, boolean isMemory) throws CException {
		String paramValue = getParameter(parameterName, String.valueOf(defaultValue));
		int value = 0;
		if (paramValue.equals("")) {
			value = defaultValue2;
		} else {
			try {
				value = Integer.parseInt(paramValue);
			} catch (Exception ex) {
				throw new CException("[" + parameterName + "] isn't int type!");
			}
		}
		if (isMemory) {
			setMemory(parameterName, String.valueOf(value));
		} else {
			removeMemory(parameterName);
		}
		return value;
	}

	public int getParameter(String parameterName, int defaultValue) throws CException {
		return getParameter(parameterName, defaultValue, 0);
	}

	public int getParameter(String parameterName, int defaultValue, boolean isMemory) throws CException {
		return getParameter(parameterName, defaultValue, 0, isMemory);
	}

	public String getParameter(HttpDataParser parser, String parameterName, String defaultValue) {
		String paramValue = parser.getParameterValue(parameterName);
		if (paramValue == null) {
			paramValue = defaultValue;
		}
		return paramValue;
	}

	public int getParameter(HttpDataParser parser, String parameterName, int defaultValue) {
		String paramValue = parser.getParameterValue(parameterName);
		if (paramValue == null) {
			return defaultValue;
		}
		if (paramValue.equals("")) {
			return defaultValue;
		}
		return Integer.parseInt(paramValue.trim());
	}

	private String readCMD() throws CException {
		String cmdstr = getParameter("CMD", "list");
		return cmdstr;
	}


	private boolean userVaildate(HttpServletRequest req, HttpServletResponse res) throws Exception {
		boolean login = false;
		String cmd = getParameter("CMD", "");
	    if (",queryAllPhotos,deleteSelectedPhoto,login,sendInformation,vehicleHistoryOrder,getAllSuppliersByLoginName,getManagerByRescueCode,getProvinceByLoginName,getAllCityByParentid,getSuppliersByParentid,findCurrentOrderDetail,vehicleChanged1,queryVehicleOrder,findAccountOrder,queryOrder,sendJoinUsMail,connection,connectionImg,signature,smsSend,verify,upload,updateVehicle,modifyIdentity,register,regist,choosedVehicleName,checkLoginName,acceptOrRecvOrder,queryRescueVehicle,managerRegist,queryCurrentFlow,updateSupplyOrderState,vehicleCurrentOrderDetail,finishedOrderDetail,arriveAgoCheck,distributeOrder,updateCompanyNotice,updateVehicleNotice,changeDistributeOrder,changedVehicle,vehicleChanged,getVehicles,updateOrderState,updateStatus,uploadOrderMileage,uploadPhoto,showOrderDetail,companyHistoryOrder,orderCount,list,getOrgList,query,find,update,cancle,getProvince,getAreaByCode,getLocal,getBrand,getOrgById,findChild,buy,".indexOf("," + cmd + ",") >= 0) {
			login = true;
		}else if(req.getServletPath().indexOf("callCenter")>=0){
			login = true;
		}else {
			session = request.getSession();
			
		}
		if (!login) {
			setNextPage("/jsp/pub/exit.jsp");
			setFailureMsg("连接超时, 或者用户已退出系统, 或者用户尚未成功登陆, 请重新登陆.");
		}
		return login;
	}

	protected void nextPage() throws CException {
		if (this.isTransition) {
			transition(cmd);
		} else if (this.nextPage.equals("no")) {
			throw new CException("no config nextpage!");
		} else if (this.nextPage.equals("need_not_nextpage")) {
			log.info("don't need nextpage");
		}
	}

	private void transition(String cmdstr) throws CException {
		if (transitionURI == null) {
			request.setAttribute("transitionURI", request.getRequestURI().toString());
		} else {
			request.setAttribute("transitionURI", transitionURI);
		}
		request.setAttribute("transitionCMD", cmdstr);
	}

	public Connection getConnection(boolean AutoCommit) throws CException {
		try {
			if (!isConnection) {
				this.conn = ConnectionPool.getConnection();
			}
			this.conn.setAutoCommit(AutoCommit);
			this.isConnection = true;
			this.isAutoCommit = AutoCommit;
		} catch (Exception ex) {
			throw new CException(ex.getMessage());
		}
		return this.conn;
	}
	

	public Connection getConnection() throws Exception {
		if (!isConnection) {
			getConnection(true);
		}
		return this.conn;
	}


	public Connection getConnection_comm() throws CException {
		try {
			if (!isConnection) {
				this.conn = ConnectionPool.getConnection_comm();
			}
			this.conn.setAutoCommit(true);
			this.isConnection = true;
			this.isAutoCommit = true;
		} catch (Exception ex) {
			throw new CException(ex.getMessage());
		}
		return this.conn;
	}

	public void closeConnection() throws Exception {
		if (this.isConnection) {
			if (!this.isAutoCommit) {
				if (this.isRollback) {
					log.info("-----------conn.rollback()");
					conn.rollback();
				} else {
					log.info("-----------conn.commit()");
					conn.commit();
				}
			}
			if (this.conn != null) {
				conn.close();
			}
			this.isConnection = false;
		}
	}

	private void saveMemory() {
		request.setAttribute("MEMOTY", this.memory);
	}

	public void setIsAutoCommit(boolean bool) {
		this.isAutoCommit = bool;
	}

	public void setNextPage(String str) {
		this.nextPage = str;
	}

	public void setTransition(String nextCMD) throws CException {
		this.isTransition = true;
		this.cmd = nextCMD;
	}

	public void setTransition(String URI, String nextCMD) throws CException {
		this.transitionURI = URI;
		this.isTransition = true;
		this.cmd = nextCMD;
	}

	public void setTransition(boolean bool, String nextCMD) throws CException {
		getConnection(bool);
		this.isTransition = true;
		this.cmd = nextCMD;
	}

	public void logInfo(String value) {
		log.info(value);
	}

	public void logDebug(String value) {
		log.debug(value);
	}

	public void logFatal(String value) {
		log.fatal(value);
	}

	public void logError(String value) {
		log.error(value);
	}

	public void setMemory(String key, String value) {
		this.memory.put(key, value);
	}

	public void setMemory(String key, Object value) {
		this.memory.put(key, value);
	}

	public void removeMemory(String key) {
		this.memory.remove(key);
	}

	public void setFailureMsg(String str) {
		this.failureMsg = str;
		this.memory.put("failureMsg", str);
	}

	public void setSuccessMsg(String str) {
		this.successMsg = str;
		this.memory.put("successMsg", str);
	}

	public void setAttribute(String name, Object o) {
		request.setAttribute(name, o);
	}

	public String getNextPage() {
		return nextPage;
	}

	public boolean isAutoCommit() {
		return isAutoCommit;
	}

	public boolean isTransition() {
		return isTransition;
	}

	public void setRollback(boolean bool) {
		this.isRollback = bool;
	}

	

	/**
	 * @param isNext
	 *            要设置的 isNext。
	 */
	public void setNext(boolean bool) {
		this.isNext = bool;
	}

	/**
	 * @return 返回 isNext。
	 */
	public boolean isNext() {
		return isNext;
	}

	public Memory getMemory() {
		return memory;
	}
	
	/**
	 * 获取数据权限sql
	 * @param contractCompanyFieldName 合同字段(包含别名),如：C.CODE; null代表没有这个条件
	 * @param rescueCompanyFieldName 服务商字段(包含别名),如：RC.CODE; null代表没有这个条件
	 * @return 权限过滤sql，有最外层括弧(); 第一个字符、最后一个字符是空格; 
	 * 			如果两个条件都需要则这两个条件是or关系,对外用括弧括起来作为一个条件；
	 *			如果两个字段都为null，系统认为不启用数据权限过滤，返回返回 (1=1) 
	 */
	/*
	public String getDataPermissionSql(String contractCompanyFieldName, String rescueCompanyFieldName){
		if (null != user){
			return BaseBean.getDataPermissionSql(user.getId(), user.getPermission_flag(), contractCompanyFieldName, rescueCompanyFieldName);
		} else {
			return BaseBean.getDataPermissionSql(null, 0, contractCompanyFieldName, rescueCompanyFieldName);
		}
	}
	*/
}
