package com.cftech.sys.security;

import com.cftech.mchaccounts.mch.dao.MchAccountsMapper;
import com.cftech.mchaccounts.mch.model.MchAccounts;
import com.cftech.sys.dao.RoleMapper;
import com.cftech.sys.dao.UserMapper;
import com.cftech.sys.model.User;
import com.cftech.sys.model.UserRole;
import com.cftech.sys.service.impl.SpringContextHolderImp;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户工具类
 * @author lisw
 * @version 2016-8-24
 */
public class UserUtils  {

	private static UserMapper userDao = SpringContextHolderImp.getBean(UserMapper.class);
	private static RoleMapper roleMapper = SpringContextHolderImp.getBean(RoleMapper.class);
	private static MchAccountsMapper mchAccountsMapper =  SpringContextHolderImp.getBean(MchAccountsMapper.class);
	public static final String CACHE_USER = "user";
	public static final String MCH_ACCOUNTS="mchaccounts";
	public static Long getmpaccounts(HttpServletRequest request)
	{
		Object obj = request.getSession().getAttribute("mpaccounts");
		if(obj==null)
		{
			return null;
		}else
		{
			return (Long)obj;
		}
	}
	
	public static Long getSession(HttpServletRequest request){
		Object obj  = request.getSession().getAttribute("memberid");
		if(obj==null){
			return null;
		}else{
			return (Long)obj;
		}
	}
	
	
	public static User getUser(){
		User user = (User)getCache(CACHE_USER);
		if (user == null){
			try{
				Subject subject = SecurityUtils.getSubject();
				SecurityRealm.Principal principal =(SecurityRealm.Principal) subject.getPrincipal();
				if (principal!=null){
					user = userDao.fetchById(principal.getId());
					putCache(CACHE_USER, user);
				}
			}catch (UnavailableSecurityManagerException e) {
				
			}catch (InvalidSessionException e){
				
			}
		}
		if (user == null){
			user = new User();
			try{
				SecurityUtils.getSubject().logout();
			}catch (UnavailableSecurityManagerException e) {
				
			}catch (InvalidSessionException e){
				
			}
		}
		return user;
	}

	public static List<String>  getUserMchAccounts(){
		List<String> mchAccounts =null;
		User user = (User)getCache(CACHE_USER);
		if (user == null){
			try{
				Subject subject = SecurityUtils.getSubject();
				SecurityRealm.Principal principal =(SecurityRealm.Principal) subject.getPrincipal();
				if (principal!=null){
					user = userDao.fetchById(principal.getId());
					//获得商户号信息
					mchAccounts = getMchAccountsByUserId(user.getId());
					putCache(CACHE_USER, user);
				}
			}catch (UnavailableSecurityManagerException e) {

			}catch (InvalidSessionException e){

			}
		}else
		{
			mchAccounts = (List<String>) getCache(MCH_ACCOUNTS);
			if(mchAccounts==null)
			{
				mchAccounts= getMchAccountsByUserId(user.getId());
			}
		}
		if (user == null){
			user = new User();
			try{
				SecurityUtils.getSubject().logout();
			}catch (UnavailableSecurityManagerException e) {

			}catch (InvalidSessionException e){

			}
		}
		return mchAccounts;
	}

	private static List<String> getMchAccountsByUserId(Long id)
	{
		List<MchAccounts> mchAccounts =  mchAccountsMapper.getAvailableMcAccounts(String.valueOf(id));
		List<String> mchAccountString = new ArrayList<String>();
		for(MchAccounts mchAccount:mchAccounts)
		{
			mchAccountString.add(mchAccount.getMchaccounts());
		}
		putCache(MCH_ACCOUNTS, mchAccountString);
		return mchAccountString;
	}

	public static User getUser(boolean isRefresh){
		if (isRefresh){
			removeCache(CACHE_USER);
		}
		return getUser();
	}


	
	// ============== User Cache ==============
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
		Object obj = getCacheMap().get(key);
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
		getCacheMap().put(key, value);
	}

	public static void removeCache(String key) {
		getCacheMap().remove(key);
	}
	
	public static Map<String, Object> getCacheMap(){
		Map<String, Object> map = Maps.newHashMap();
		try{
			Subject subject = SecurityUtils.getSubject();
			SecurityRealm.Principal principal = (SecurityRealm.Principal)subject.getPrincipal();
			return principal!=null?principal.getCacheMap():map;
		}catch (UnavailableSecurityManagerException e) {
			
		}catch (InvalidSessionException e){
			
		}
		return map;
	}

}
