package cc.smtweb.framework.core.session;

import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.util.IpAddrUtil;
import lombok.Getter;
import lombok.Setter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * 用户会话缓存，前端调用API时传输 Auto_Token 参数来查找用户会话
 *
 * @author xkliu
 */
@Getter
@Setter
public class UserSession implements Serializable {
    private static final long serialVersionUID = 3854315462714888716L;
    //
    private String sessionId = null; //sessionId
    //登录时间
    private Long loginTimeMillis;
    //最后请求时间
    private Long lastTimeMillis = 0L;
    //ID
    private String loginIp;
    // 用户ID
    private long userId;
    // 用户等级
    private long userLevel = SwEnum.UserLevel.inner.value;
    // 当前机构ID
    private long partyId;
    // 当前部门
    private long deptId;
    // 站点ID
    private long siteId;
    // 终端类型
    private byte terminalType;

    public UserSession() {

    }

    public UserSession(HttpServletRequest request, long user_id) {
        this(request, user_id, (byte) 0);
    }

    public UserSession(HttpServletRequest request, long user_id, byte terminalType) {
        this.loginIp = IpAddrUtil.getIpAddr(request);
        this.userId = user_id;
        this.terminalType = terminalType;

        HttpSession session = request.getSession(true);
        if (user_id > 0L) session.setAttribute(SwConsts._LOGIN_USER_ID_IN_SESSION, getUserKey());
        this.sessionId = session.getId();
        this.loginTimeMillis = System.currentTimeMillis();
        this.lastTimeMillis = this.loginTimeMillis;
    }

    //模拟
    public UserSession(long user_id) {
        this(user_id, (byte) 0);

    }

    public UserSession(long user_id, byte terminalType) {
        this.userId = user_id;
        this.terminalType = terminalType;
        this.loginTimeMillis = System.currentTimeMillis();
    }

    public static UserSession createSys() {
        UserSession us = new UserSession();
        us.userId = 1L;
        us.partyId = 1L;
        us.terminalType = 0;
        return us;
    }

    public String getUserKey() {
        return userId + "_" + terminalType;
    }
}
