package com.blueland.bpm.manage.util;

import cn.hutool.core.util.StrUtil;
import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.common.util.SysConfig;
import com.blueland.bpm.identity.RoleService;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.Role;
import com.blueland.bpm.identity.model.User;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class BaseUser {
	private static BaseUser baseUser=new BaseUser();
	private static RoleService roleService;
	private static UserService userService;
	private BaseUser(){

	}
	public static BaseUser getInstance(){
		roleService=(RoleService)ApplicationContextHolder.getBean("roleServiceImpl");
		userService=(UserService)ApplicationContextHolder.getBean("userServiceImpl");
		return baseUser;
	}
	public void setRoleService(RoleService roleService) {
		BaseUser.roleService = roleService;
	}
	/**
	 * 系统管理员
	 */
	public static String ROLE_SYSROLE = "sysrole";
	public static String ROLE_EBPMADMIN="ebpmAdmin";
	public String getUserId(HttpServletRequest request) {
		//Cookie
		String sUserId = getCookieUser(request);
		return sUserId ;
	}


	public   User backSSO(HttpServletRequest request,HttpServletResponse response,String userId){
		if(StringUtils.isEmpty(userId)){
			userId=request.getHeader("iv-user");
		}
		User loginUser=null;
		if(StringUtils.isEmpty(userId)){
			try {
				loginUser = getSessionUser(request);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			loginUser = userService.getUserById(userId);
			baseUser.cleanCookieUser(request,  response);
			baseUser.setCookieUser(response, BaseUser.toUpperCase(userId));
			System.out.println(userId);
			baseUser.saveUserToSession(request, loginUser, null);
		}
		return loginUser;
	}

	public String getCookieUser (HttpServletRequest request){

		Cookie [] cookie = request.getCookies();

		if(null!=cookie){
			for(int i=0,len=cookie.length; i<len; i++){
				if(cookie[i].getName().equalsIgnoreCase(MyContants.userId)){
					String userId = cookie[i].getValue().toString();
					return toUpperCase(userId);
				}
			}
		}

		return null;
	}


	public void cleanCookieUser (HttpServletRequest request,HttpServletResponse response) {

		Cookie[] cookies=request.getCookies();
		if(cookies!=null){
			for(int i=0,len=cookies.length; i<len; i++)
			{
				Cookie cookie=cookies[i];
				if(cookie!=null&&MyContants.userId.equals(cookie.getName())){
					cookie.setMaxAge(0);
					cookie.setValue(null);
				}
			}
		}

	}



	public void setCookieUser  (HttpServletResponse response,String userId) {
		Cookie mycookie=new Cookie(MyContants.userId,toUpperCase(userId));
		mycookie.setMaxAge(Integer.valueOf(MyContants.MAX_COOKIE));//????Cookie????????,??cookie??2????��
		mycookie.setPath("/");
		response.addCookie(mycookie);
	}
	public String getSessionUser(HttpServletRequest request,String userId){
		HttpSession hs = request.getSession();
		String sUserId = (String)hs.getAttribute(MyContants.userId);
		if (sUserId!=null && sUserId.length()>0)
			sUserId = toUpperCase(sUserId);
		return sUserId;

	}



	public void setUser(HttpServletRequest request,HttpServletResponse response,String UserID)
	{

		Cookie ck=new Cookie(MyContants.userId,toUpperCase(UserID));
		ck.setMaxAge(Integer.valueOf(MyContants.MAX_COOKIE));//cookie????10��?
		String path1 = request.getContextPath();
		ck.setPath(path1);
		response.addCookie(ck);


	}




	//	 ????????
	public static String toUpperCase(String source){

		String sour = source;
		try{
			sour = sour.toUpperCase();
		}catch(Exception ex){
			sour = source;
		}
		return sour;
	}

	public  void saveUserToSession(HttpServletRequest request,User loginUser, List<ApplicationEntity> applications){
		HttpSession session=request.getSession(true);
		try{
			boolean isAdmin= isSysrole(loginUser);
			boolean isEbpmAdmin = isEbpmAdmin(loginUser);
			session.setAttribute(ROLE_SYSROLE, isAdmin);
			session.setAttribute(ROLE_EBPMADMIN, isEbpmAdmin);
			session.setAttribute(MyContants.LOGIN_SESSION_USER, loginUser);
//			Map<String,String> appMaps=new HashMap<String,String>();
//			appMaps.put("","所有系统");
//			appMaps.put("STDD_SYS","标准化系统");
//			appMaps.put("WORKDOC_SYS","公文系统");
//			appMaps.put("WORKORDER_SYS","工单系统");
//			if(isAdmin){
//				session.setAttribute(MyContants.APP_ID_KEY, "");
//			}else{
//				session.setAttribute(MyContants.APP_ID_KEY, "STDD_SYS");
//			}
//			session.setAttribute("APP_MAPS", appMaps);
			if(applications!=null){
				session.setAttribute("APP_MAPS", applications);
				saveLoginUserAppId( applications.get(0), request);
			}
			session.setMaxInactiveInterval(Integer.valueOf(MyContants.MAX_SESSION));
		}catch(Throwable e){
			e.getMessage();
		}
	}

	public String getLoginUserAppId(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String appId = (String) session.getAttribute(MyContants.APP_ID_KEY);
		return appId;
	}

	public ApplicationEntity getLoginUserApplication(HttpServletRequest request){
		HttpSession session = request.getSession();
		ApplicationEntity application = (ApplicationEntity) session.getAttribute(MyContants.APPLICATION);
		return application;
	}

	public void saveLoginUserAppId(ApplicationEntity application,HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		session.setAttribute(MyContants.APP_ID_KEY,application.getAppId());
		session.setAttribute(MyContants.APPLICATION, application);
	}

	public  void removeUserToSession(HttpServletRequest request){
		HttpSession session=request.getSession(false);
		try{
			User userData=(User)session.getAttribute(MyContants.LOGIN_SESSION_USER);
			if(userData!=null){
				userData=null;
			}
			session.removeAttribute(MyContants.USER_ROLES);
			session.removeAttribute(MyContants.LOGIN_SESSION_USER);
			session.invalidate();

		}catch(Throwable e){
			e.getMessage();
		}
	}
	public List getUserRoles(String userId){
		//return copyRoleData(orgSchema.getUserRoles(userId));
		return null;
	}
	public  boolean isInRole(HttpServletRequest request,List roles,String purviewName){
		
		/*try {
			if(getSessionUser(request)==null){
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(StringUtils.isNull(roles)){
			return false;
		}
		//HttpSession session=request.getSession();
		//Boolean isAdmin=(Boolean) session.getAttribute(MyContants.KH_COMPANY_ADMIN_ROLE);
		if(isAdmin!=null&&isAdmin.booleanValue()){
			return true;
		}else if(MyContants.KH_ORG_ADMIN_ROLE.equals(purviewName)){
			Boolean isOrgRole=(Boolean) session.getAttribute(MyContants.KH_ORG_ADMIN_ROLE);
			return (isOrgRole!=null?isOrgRole.booleanValue():false);
		}
		else{
			
			if(roles!=null){
				for(int i=0;i<roles.size();i++){
					RoleData role=(RoleData)roles.get(i);
					if(role.getName().equalsIgnoreCase(purviewName)){
						return true;
					}
				}
			}
		//}
*/		return false;
	}



	//
//	
	public User getSessionUser(HttpServletRequest request)throws Exception{
		User loginUser=null;
		loginUser=(User)request.getSession().getAttribute(MyContants.LOGIN_SESSION_USER);
		return loginUser;

	}
	/**
	 * 是否系统管理员
	 */
	public static boolean isSysrole(User user){
		return checkRoleByUserId(user.getUserId(), ROLE_SYSROLE);
	}
	/**
	 * 是否流程管理员
	 */
	public static boolean isEbpmAdmin(User user){
		return checkRoleByUserId(user.getUserId(), ROLE_EBPMADMIN);
	}

	/**
	 * 是否流程管理员
	 */
	public static boolean isEbpmAdminSession(HttpServletRequest request){
		try {
			return (boolean) request.getSession().getAttribute(ROLE_EBPMADMIN);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 是否流程管理员
	 */
	public static boolean isEbpmAdmin(HttpServletRequest request){
		User user=null;
		try {
			user = BaseUser.getInstance().getSessionUser(request);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return checkRoleByUserId(user.getUserId(), ROLE_EBPMADMIN);
	}
	private static boolean checkRoleByUserId(String userId,String roleFlag){
		try{
			List<Role> userRoles=roleService.findRoleByUserId(userId);
			for(Role role : userRoles){
				if (roleFlag.equals(role.getRoleId())||(role.getRoleId().equals("1")&&roleFlag.equals(ROLE_EBPMADMIN))){
					return true;
				}
			}}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}


}