package com.hai.common.security;

import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserCenter {

	private static Logger log = LoggerFactory.getLogger(UserCenter.class);

	@Autowired
    private RedisUtil redisUtil;

	private final String COOKIE_FIELD = "_ida";
	private final int EXPIRE = 3600 * 24 * 7;//cookie过期时间为7天

    /**
     * 判断用户是否登录,并且不能单个用户同时登录
     * @param request
     * @return boolean
     * @throws Exception
     */
    public boolean isLogin(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if(StringUtils.isBlank(token)){
            Cookie cookie = CookieUtil.getCookieByName(request, COOKIE_FIELD);
            if(cookie != null && StringUtils.isNotBlank(cookie.getValue())){
                token = cookie.getValue();
            }
        }
        if(StringUtils.isBlank(token)){
        	return false;
        }
        try {
            if (!StringUtils.isEmpty(token)) {
                SessionObject cacheStr = (SessionObject)redisUtil.get(token);
                if (cacheStr != null) {
                    redisUtil.expire(token,EXPIRE);
                    return true;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
	
    /**
     * 
     * @Title: isTokenLogin   
     * @Description: 支持token形式的校验登录 
     * @author: 机器猫 
     * @param: @param token
     * @param: @return
     * @param: @throws Exception      
     * @return: boolean      
     * @throws
     */
    public boolean isTokenLogin(String token){
    	 try {
    		 log.error("------------------------------" + token);
             if(!StringUtils.isEmpty(token)){
                 SessionObject cacheStr = (SessionObject)redisUtil.get(token);
                 if (cacheStr != null) {
                     redisUtil.expire(token,EXPIRE);
                     return true;
                 }
             }
             return false;
		} catch (Exception e) {
			log.error("isTokenLogin failed",e);
			return false;
		}
    }
    
    public String read(HttpServletRequest request){
        Cookie cookie = CookieUtil.getCookieByName(request, COOKIE_FIELD);
        if(cookie == null){
            return null;
        }
        return cookie.getValue();
    }


    public <E> E getSessionModel(Class<E> clazz){
        if (RequestContextHolder.getRequestAttributes()!=null) {
            HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            SessionObject sessionObject = getSessionObject(req);
            if (sessionObject == null){
                return null;
            }
            if (clazz.equals(sessionObject.getObject().getClass())){
                return (E)sessionObject.getObject();
            }
        }
        return null;
    }

    public SessionObject getSessionObject(HttpServletRequest request) {
    	String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            if (StringUtils.isNotBlank(read(request))) {
                token = read(request);
            }
        }
        if (redisUtil.get(token) == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.USE_VISIT_ILLEGAL, "");
        }
        return (SessionObject) redisUtil.get(token);
    }

    /**
     * @param request
     * @param response
     * @param response
     * @throws Exception
     */
    public void save(HttpServletRequest request, HttpServletResponse response, SessionObject seObj) throws Exception{
        CookieUtil.saveCookie(request, response, COOKIE_FIELD, seObj.getUniqueCode(), EXPIRE);
        redisUtil.set(seObj.getUniqueCode(), seObj, EXPIRE);
    }
    
    /**
     * 刷新cookie信息
     * 
     * @param request
     * @param response
     * @throws Exception 
     */
    public void refreshCookie(HttpServletRequest request, HttpServletResponse response) throws Exception{
        CookieUtil.refreshCookie(request, response, COOKIE_FIELD, EXPIRE);
    }

    /**
     * @param request
     * @param response
     * @throws Exception
     */
    public void remove(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(token)){
            //通过token方式登录
            redisUtil.del(token);
            CookieUtil.delCookie(response, COOKIE_FIELD);
        }else{
            String jo = read(request);
            if(StringUtils.isNotBlank(jo)){
                redisUtil.del(jo);
                CookieUtil.delCookie(response, COOKIE_FIELD);
            }
        }
    }



    
}
