package com.fos.modules.user.service;

import com.fos.core.security.Digests;
import com.fos.core.utils.Encodes;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fos.core.base.BaseBean;
import com.fos.core.base.CurdService;
import com.fos.modules.user.bean.UserBean;
import com.fos.modules.user.dao.UserDao;
import com.fos.modules.user.entity.UserEntity;


@Service
public class UserService extends CurdService<UserDao,UserEntity> {
	
	//登录时验证用户名密码是否正确
	public UserEntity loginUser(UserBean userBean){
	
	    UserEntity userEntity = dao.loginUser(userBean);
		return userEntity;

	}


	public static final int HASH_INTERATIONS = 1024;
	/**
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @return 验证成功返回true
	 */
	public static boolean validatePassword(String plainPassword, String password) {
		String plain = Encodes.unescapeHtml(plainPassword);
		byte[] salt = Encodes.decodeHex(password.substring(0,16));
		byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
	}

	/**
	 * 登录时更新登录状态
	 * @param userBean
	 */
	@Transactional(readOnly = false)
	public void updateStatus(UserBean userBean){
	    dao.updateStatus(userBean);
	}
	
	/**
	 * 心跳包更新登录状态
	 * @param loginName
	 * @param loginStatus
	 */
    @Transactional(readOnly = false)
    public void checkLoginStatus(String loginName, String loginStatus){
        dao.checkLoginStatus(loginName, loginStatus);
    }
    
    /**
     * 轮询更新登录状态
     * @param operationTime
     */
    @Transactional(readOnly = false)
    public void logoutStatus(String operationTime){
        dao.logoutStatus(operationTime);
    }
    
    /**
     * 登出接口
     * @param loginName
     * @param loginStatus
     */
    @Transactional(readOnly = false)
    public void logout(String loginName, String loginStatus){
        dao.logout(loginName, loginStatus);
    }
}
