package com.ced.sip.common.action.epp;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.sip.system.biz.ISysUserInoutLogBiz;
import com.ced.sip.common.BaseDataInfosUtil;
import com.ced.sip.common.TableStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.entity.SessionInfo;
import com.ced.sip.common.entity.SessionUser;
import com.ced.sip.common.utils.PasswordUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.expert.biz.IExpertBiz;
import com.ced.sip.expert.entity.Expert;
import com.ced.sip.system.biz.IDepartmentsBiz;
import com.ced.sip.system.biz.ISysMenuBiz;
import com.ced.sip.system.biz.IUsersBiz;
import com.ced.sip.system.entity.Departments;
import com.ced.sip.system.entity.OrgUser;
import com.ced.sip.system.entity.SysMenu;
import com.ced.sip.system.entity.SysUserInoutLog;
import com.ced.sip.system.entity.Users;

public class ValidateUserAction extends BaseAction {
	private IUsersBiz iUsersBiz  ;
	private IDepartmentsBiz iDepartmentsBiz;
	private ISysUserInoutLogBiz iSysUserInoutLogBiz ;	
	private ISysMenuBiz iSysMenuBiz;
	
	private IExpertBiz iExpertBiz;
	
	
	
	Map<String, Object> map = new HashMap<String, Object>();	
	private Users ur ;
	private SessionUser sessionUser;
 	private String errorMsg ;
 	private String validateCode;  //验证码
	
	/**
	 * 获取多级菜单
	 * @param roleIds  用户角色id
	 * @return
	 * @throws BaseException
	 */
	public List<SysMenu> queryAllMenuList(Long userId) throws BaseException {
		//根据用户id查询所有权限菜单
		List<SysMenu> allSysMenu = iSysMenuBiz.getTreeSysMenuListByUserId(userId+"");
		
		//定义第一级菜单集合
		List<SysMenu> mainMenuList=new ArrayList<SysMenu>();
		//定义第一级菜单节点
		List<String> menuCodeList = new ArrayList<String>();
		for(SysMenu menu:allSysMenu)
		{
			menuCodeList.add(menu.getMenuCode());
			if(menu.getPmenuCode().equals("999999") && menu.getMenuFolderFlag().equals("0"))
			{
				mainMenuList.add(menu);
			}
		}
		
		//所有父级节点
		Set<String> parentMenuCodeSet = new HashSet<String>();
		for (int i = 0; i < allSysMenu.size(); i++) {
			parentMenuCodeSet.add(allSysMenu.get(i).getPmenuCode());
		}
		//
		Set<String> parentMenuCodeSet2 = new HashSet<String>();
		for (int i = 0; i < allSysMenu.size(); i++) {
			parentMenuCodeSet2.add(allSysMenu.get(i).getMenuCode());
		}

		List<SysMenu> SysMenuList = new ArrayList<SysMenu>();
		for (SysMenu entity : mainMenuList) {
			SysMenu SysMenu = entity;
			//获取第二级菜单集合
			List<SysMenu> subSysMenuList = iSysMenuBiz.getFuSysMenuList(entity.getMenuCode());
			List<SysMenu> resultSubSysMenuList = new ArrayList<SysMenu>();
			
			for (int i = 0; i < subSysMenuList.size(); i++) {
				if (menuCodeList.contains(subSysMenuList.get(i).getMenuCode())) {
					resultSubSysMenuList.add(subSysMenuList.get(i));
					if (parentMenuCodeSet.contains(subSysMenuList.get(i).getMenuCode())) {
						//获取第三级菜单集合
						List<SysMenu> subSubSysMenuList = iSysMenuBiz.getFuSysMenuList(subSysMenuList.get(i).getMenuCode());
						List<SysMenu> subSubSysMenuList2= new ArrayList<SysMenu>();
						//判断该用户所拥有的第三级菜单
						for(SysMenu sm:subSubSysMenuList)
						{
							if(parentMenuCodeSet2.contains(sm.getMenuCode()))
							{
								subSubSysMenuList2.add(sm);
							}
						}
						subSysMenuList.get(i).setSubAuthorityList(subSubSysMenuList2);
					}
				}
			}
			
			SysMenu.setSubAuthorityList(resultSubSysMenuList);
			
			if (subSysMenuList.size() == 0) {
				SysMenuList.add(null);
			} else {
				SysMenuList.add(SysMenu);
			}
		}
		
		return SysMenuList;
	}
	
	/**
	 * 用户登陆校验
	 * @return
	 * @throws ServletException
	 */
	public String verifyLogin() throws BaseException {
		String code="";
		String rUrlPage 		= "invalidlogin" ;
		boolean falg=false;
		List userList =null;		
		try {   
				String validateCode =this.getRequest().getParameter("validateCode");
				code=(String) this.getRequest().getSession().getAttribute("randCode");
				if(StringUtil.isBlank(code)) falg=true; else falg=StringUtil.convertNullToBlank(validateCode).equals(code); //验证码错误
				if(!falg){
					this.getRequest().setAttribute("errorMassge", "验证码有误，请重新输入");
					rUrlPage = "exit" ;
				}else{
					if(ur != null){
					ur.setUserName(ur.getJ_username());
					ur.setUserPassword(PasswordUtil.encrypt( ur.getJ_password().trim() ) ) ;
					userList= iUsersBiz.getUsersList( ur ) ;
					}
				}
		        if(falg&&userList != null && userList.size()>0 ) { // 通过用户校验, 保存用户信息到session并返回主页面
						Users user 			= (Users) userList.get( 0 ) ;
						
						if( TableStatus.COMMON_STATUS_VALID.equals( user.getIsUsable() ) ){//判断用户是否有效	
							SessionInfo info = new SessionInfo() ;
							
							//判断此用户的类别，3普通用户，1部门经理  2高层领导  4分管领导 首先从缓存里面取,如果缓存里面没有值,则去查询
							int userType=BaseDataInfosUtil.convertLoginNameToUserType(user.getUserName());
							if(userType==0){
								
								userType=3;
								
								//部门经理判断
								List<Departments> list_dept = iDepartmentsBiz.getSignUsersList();
								for(Departments departments:list_dept){
									if(StringUtil.convertNullToBlank(departments.getDepLeaderId()).equals(user.getUserId())){
										userType=1;
										break;
									}
								}
								//分管领导判断
								List<Departments> list_com_dept = iDepartmentsBiz.getComSignUsersList();
								for(Departments departments:list_com_dept){
									if(StringUtil.convertNullToBlank(departments.getDepLeaderId()).equals(user.getUserId())){
										userType=4;
										break;
									}
								}
								//高层领导判断
							   OrgUser orgUser=new OrgUser();
					           orgUser.setOrgCode(TableStatus.Leader);
								List list=iUsersBiz.getUsersListByOrgUser(orgUser);
								for(int i=0;i<list.size();i++){
									Users ur = (Users) list.get(i);
									if(StringUtil.convertNullToBlank(ur.getUserName()).equals(user.getUserName())){
										userType=2;
										break;
									}
								}
							}
                            user.setUserType(userType);		
							BaseDataInfosUtil.updateUserCache("update", user);
							
							info.setUsers( user );
							
							info.setDept( iDepartmentsBiz.getDepartments( user.getDepId() ) ) ;
							
							List<Departments> deptIdList=iDepartmentsBiz.getDepIdsByUserId(user.getUserName());  //该用户所有权限部门
							info.setDeptIdList(deptIdList);
							
							List<Departments> leaderList=iDepartmentsBiz.getDepartsToUserId(user.getUserId());  //该用户是部门领导或是分管领导
							info.setLeaderList(leaderList);
							
							//查询该用户所有的权限部门信息
							List<Departments> departList=new ArrayList<Departments>();
							Departments dept = null;
							dept = this.iDepartmentsBiz.getDepartments(user.getDepId());
							departList.add(dept);
							if(deptIdList!=null|| deptIdList.size()!=0){
								for(Departments de:deptIdList){
									if(StringUtil.isNotBlank(de.getDepId())){
										dept = this.iDepartmentsBiz.getDepartments(de.getDepId());
										departList.add(dept);
									}
								}
							}
							info.setDepartList(departList);
							
							sessionUser=new SessionUser();
							sessionUser.setType(TableStatus.COMMON_TYPE_0);
							sessionUser.setLoginName(user.getUserName());
							sessionUser.setId(user.getUserId());
							sessionUser.setName(user.getUserChinesename());
							sessionUser.setComId(user.getComId());
							info.setSessionUser(sessionUser);
							
							UserRightInfoUtil.setSessionInfo(info, this.getRequest() ) ;
							ur.setUserChinesename(user.getUserChinesename());
							
							rUrlPage = "main";
							//获取所有菜单集合
							List<SysMenu> allMenuList = queryAllMenuList(user.getUserId());
							this.getRequest().setAttribute("authorityList", allMenuList);
							
							String ip = this.getRequest().getHeader("X-Real-IP");  
							SysUserInoutLog tSysUserInoutLog=new SysUserInoutLog( info.getUsers().getUserName(), info.getUsers().getUserChinesename(),
									ip, new Date(), this.getSession().getId().toString(), TableStatus.COMMON_STATUS_VALID,TableStatus.COMMON_TYPE_0 );
							// 保存登录日志信息
							iSysUserInoutLogBiz.saveSysUserInoutLog(tSysUserInoutLog);
							this.getRequest().getSession().setAttribute("uiId", tSysUserInoutLog.getUilId());
							
						}else {
							rUrlPage = "invalidlogin" ;
						}	
					}else{ // 校验失败, 返回登陆页面, 提示错误信息
						errorMsg = "incorrectPassword"; // 姓名或密码输入错误！
						this.getRequest().setAttribute("errorMassge", "用户名或密码输入错误！，请重新输入");
						rUrlPage = "exit" ;
					}
		} catch (Exception e) {
			log.error("用户登陆校验错误！", e);
			throw new BaseException("用户登陆校验错误！", e);
		}
		return rUrlPage  ;
	}
	
	/**
	 * 用户退出
	 * @return
	 * @throws ServletException
	 */
	public String exit( ) throws BaseException {
		String page="exit";
		try {
			String from=this.getRequest().getParameter("from");
			HttpSession session = this.getSession() ;
			
			iSysUserInoutLogBiz.userLogoutLog(session.getId().toString());
			
			for (Enumeration e = session.getAttributeNames() ; e.hasMoreElements() ;) {
				session.removeAttribute((String)e.nextElement());
		    }
			//触屏版使用
            if(StringUtil.isNotBlank(from)) page+="Mobile";
            
		} catch (Exception e) {
			log.error("用户退出错误！", e);
			throw new BaseException("用户退出错误！", e);

		}
		return page ;
	}
	/**
	 * 用户登录超时 
	 */
	public String timeout() throws BaseException{
		try{
			
			
		} catch (Exception e) {
			log.error("用户登录超时 ！", e);
			throw new BaseException("用户登录超时 ！", e);
		}
		return "timeout" ;
	}
	/**
	 * 评委登陆校验
	 * @return
	 * @throws ServletException
	 */
	public String verifyBidsJudgerLogin() throws BaseException {
		String rUrlPage 		= "invalidlogin" ;
		String validateCode =this.getRequest().getParameter("validateCode");
		String code=(String) this.getRequest().getSession().getAttribute("randCode");
		boolean falg=validateCode.equals(code);
		try {
			   if(falg){
				    Expert expert = new Expert();
				    expert.setExpertLoginName(ur.getJ_username());
				    expert.setExpertPassword(PasswordUtil.encrypt(ur.getJ_password()));
					List nameList = this.iExpertBiz.getExpertList(expert);
					if(nameList!=null&&nameList.size()>0){
						    expert=(Expert)nameList.get(0);
						    
							SessionInfo info = new SessionInfo() ;	
							sessionUser=new SessionUser();
							sessionUser.setType(TableStatus.COMMON_TYPE_2);
							sessionUser.setLoginName(expert.getExpertLoginName());
							sessionUser.setId(expert.getExpertId());
							sessionUser.setName(expert.getExpertName());
							info.setSessionUser(sessionUser);
							
							UserRightInfoUtil.setSessionInfo(info, this.getRequest() ) ;
							SysUserInoutLog tSysUserInoutLog=new SysUserInoutLog( expert.getExpertLoginName(), expert.getExpertName(),
									this.getRequest().getRemoteAddr(), new Date(), this.getSession().getId().toString(), TableStatus.COMMON_STATUS_VALID,TableStatus.COMMON_TYPE_2 );
							// 保存登录日志信息
							iSysUserInoutLogBiz.saveSysUserInoutLog(tSysUserInoutLog);
							this.getRequest().getSession().setAttribute("uiId", tSysUserInoutLog.getUilId());
							rUrlPage = "evaluateIndex";
						}else{
							this.getRequest().setAttribute("errorMassge", "姓名或密码输入错误！，请重新输入");
							rUrlPage = "exit" ;
						}
					
				}else{
					this.getRequest().setAttribute("errorMassge", "验证码有误，请重新输入");
					rUrlPage = "exit" ;
				}
		} catch (Exception e) {
			log.error("评委登陆校验错误！", e);
			throw new BaseException("评委登陆校验错误！", e);
		}
		return rUrlPage  ;
	}
	public IUsersBiz getIUsersBiz() {
		return iUsersBiz;
	}

	public void setIUsersBiz(IUsersBiz usersBiz) {
		iUsersBiz = usersBiz;
	}

	public IDepartmentsBiz getIDepartmentsBiz() {
		return iDepartmentsBiz;
	}

	public void setIDepartmentsBiz(IDepartmentsBiz departmentsBiz) {
		iDepartmentsBiz = departmentsBiz;
	}
	
	public ISysUserInoutLogBiz getiSysUserInoutLogBiz() {
		return iSysUserInoutLogBiz;
	}

	public void setiSysUserInoutLogBiz(ISysUserInoutLogBiz iSysUserInoutLogBiz) {
		this.iSysUserInoutLogBiz = iSysUserInoutLogBiz;
	}

	public Users getUr() {
		return ur;
	}
	
	public void setUr(Users ur) {
		this.ur = ur;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public ISysMenuBiz getiSysMenuBiz() {
		return iSysMenuBiz;
	}

	public void setiSysMenuBiz(ISysMenuBiz iSysMenuBiz) {
		this.iSysMenuBiz = iSysMenuBiz;
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	public IUsersBiz getiUsersBiz() {
		return iUsersBiz;
	}

	public void setiUsersBiz(IUsersBiz iUsersBiz) {
		this.iUsersBiz = iUsersBiz;
	}

	public IDepartmentsBiz getiDepartmentsBiz() {
		return iDepartmentsBiz;
	}

	public void setiDepartmentsBiz(IDepartmentsBiz iDepartmentsBiz) {
		this.iDepartmentsBiz = iDepartmentsBiz;
	}

	public IExpertBiz getiExpertBiz() {
		return iExpertBiz;
	}

	public void setiExpertBiz(IExpertBiz iExpertBiz) {
		this.iExpertBiz = iExpertBiz;
	}
	
	
}
