package com.community.huiju.common.base;

import com.community.commom.constant.Constant;
import com.community.commom.session.UserElement;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.vo.ToUserVO;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;

/**
 * @author FXF
 * @date 2018-12-18
 */
@Slf4j
public class BaseController {
    
    /**
     * 获取 UserElement
     * @param session
     * @return
     */
    protected UserElement getUserElement(HttpSession session){
        log.info("获取sessionId: {}", session.getId());
        UserElement userElement = (UserElement) session.getAttribute(Constant.WEB_USER_SESSION);
        if (null == userElement) {
            throw new WisdomException("用户凭证不存在!");
        }
        return userElement;
    }

    /**
     * 获取 UserElement
     * @param session
     * @return
     */
    protected void setUserElement(HttpSession session, ToUserVO userVO){
        log.info("获取sessionId: {}", session.getId());
        UserElement userElement = new UserElement();
        userElement.setId(userVO.getId());
        userElement.setCommunityId(userVO.getCommunityId());
        userElement.setEmail(userVO.getEmail());
        userElement.setLoginName(userVO.getLoginName());
        userElement.setUserName(userVO.getUserName());
        userElement.setStatus(userVO.getStatus());
        userElement.setLoginType(Constant.WEB_LOGIN_TYPE);

        session.setAttribute(Constant.WEB_USER_SESSION, userElement);
    }


    /**
     * 清除 用户 session
     * @param session
     */
    protected void cleanUserSession(HttpSession session){
        log.info("退出登陆!");
        UserElement userElement = (UserElement) session.getAttribute(Constant.WEB_USER_SESSION);
        if (null != userElement) {
            session.setAttribute(Constant.WEB_USER_SESSION, null);
        }
    }

}
