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.UserVO;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

/**
 * @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, UserVO 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);
        }
    }

    /**
     * 发送响应流方法
     */
    protected void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
//            response.setContentType("application/octet-stream;charset=ISO8859-1");
//            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
//            response.addHeader("Pargam", "no-cache");
//            response.addHeader("Cache-Control", "no-cache");

            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
