package com.community.huiju.controller;

import com.community.commom.constant.Constant;
import com.community.commom.session.UserElement;
import com.community.huiju.exception.WisdomException;
import com.community.huiju.model.ToCommunities;
import com.community.huiju.service.CommunityServiceI;
import com.community.huiju.vo.TaUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;

/**
 * 公共 controller
 */
@Slf4j
public class BaseController {

    @Autowired
    private CommunityServiceI community;

    /**
     * 校验小区是否存在
     * @return
     */
    protected boolean check(Integer communityId){
        ToCommunities toCommunities = community.getByCommunityId(communityId);
        if (null != toCommunities) {
            return true;
        }
        return false;
    }

    /**
     * 设置用户 session
     * @param userVO
     * @param session
     */
    protected void setUserElement(TaUserVO userVO, HttpSession session) {
        if (null == userVO) {
            throw new WisdomException("用户信息不能为空!");
        }

        log.info("用户当前sessionId：{}, 设置的用户信息: {}", session.getId(), userVO);
        UserElement userElement = new UserElement();
        BeanUtils.copyProperties(userVO,userElement);
        userElement.setLoginType(Constant.APP_LOGIN_TYPE);
        session.setAttribute(Constant.APP_USER_SESSION,userElement);
        userVO.setToken(session.getId());
    }

    /**
     * 获取用户 session
     * @param session
     * @return
     */
    protected UserElement getUserElement(HttpSession session) {
        UserElement userElement = (UserElement) session.getAttribute(Constant.APP_USER_SESSION);
        log.info("用户当前sessionId：{}, 设置的用户信息: {}", session.getId(), userElement);
        if (null == userElement) {
            throw new WisdomException("用户 session 不存在！");
        }
        return userElement;
    }

    /**
     * 删除 用户 session
     * @param session
     */
    protected void removeUserElement(HttpSession session) {
        log.info("用户当前sessionId：{}", session.getId());
        session.removeAttribute(Constant.APP_USER_SESSION);
    }

}
