
package org.tio.sitexxx.service.service.base;

import org.tio.sitexxx.service.model.main.LoginLog;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.model.main.UserLastLoginTime;
import org.tio.sitexxx.service.vo.Const;
import org.tio.utils.cache.CacheUtils;
import org.tio.utils.hutool.StrUtil;

import java.util.Date;

/**
 * @author tanyaowu 
 * 2016年9月15日 下午1:42:50
 */
public class LoginLogService {
	public static final LoginLogService	me	= new LoginLogService();
	public static final LoginLog		dao	= new LoginLog().dao();

	public void add(LoginLog loginLog) {
		updateTime(loginLog.getUid());
		loginLog.save();
	}

	public void updateTime(Integer uid){
		if (uid != null) {
			UserLastLoginTime time =UserLastLoginTime.dao.findFirst("select * from user_last_login_time where uid ="+uid);
			if (time == null) {
				time = new UserLastLoginTime();
				time.setUid(uid);
				time.setCreateTime(new Date());
				time.replaceSave();
			} else {
				time.setCreateTime(new Date());
				time.update();
			}
		}
	}
	//发展起来了 创业
	//没发展起来 领工资

	/**
	 * 根据 sessionid获取最近一次登录日志信息
	 * @param sessionid
	 * @return
	 * @author tanyaowu
	 */
	public LoginLog selectLastLoginLog(String sessionid) {
		if (StrUtil.isBlank(sessionid)) {
			return null;
		}

		String cacheKey = "login_log.sessionid." + sessionid;
		return CacheUtils.get(Const.CacheTime.SECOND_60, null, cacheKey, true, () -> {
			String sql = "SELECT * FROM `login_log` where sessionid = ? order by time desc LIMIT 0, 1";
			return dao.findFirst(sql, sessionid);
		});
	}

	public Date selectLastTimeByUid(Integer uid){
		UserLastLoginTime time = UserLastLoginTime.dao.findFirst("SELECT * FROM `user_last_login_time` where uid = "+uid);
		if (time == null) {
			return null;
		}
		return time.getCreateTime();
	}

	/**
	 * 根据 sessionid获取最近一次登录的用户
	 * @param sessionid
	 * @return
	 * @author tanyaowu
	 */
	public User selectLastLoginUser(String sessionid) {
		LoginLog loginLog = selectLastLoginLog(sessionid);
		if (loginLog == null) {
			return null;
		}

		return UserService.ME.getById(loginLog.getUid());
	}
}
