package com.tarena.oss.user.dao;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tarena.oss.user.pojo.User;
import com.tarena.oss.util.PageParameter;
public class UserMgmtDAOHibernate extends HibernateDaoSupport implements UserMgmtDAO {
	
	/**
	 * 删除一个帐务帐号
	 */
	public void deleteUser(User user) {
		this.getHibernateTemplate().delete(user);
	}

	/**
	 * 插入一个帐务帐号
	 */
	public void insertUser(User user) {
		this.getHibernateTemplate().save(user);
	}
	
	/**
	 * 更新一个帐务帐号
	 */
	public void updateUser(User user) {
		this.getHibernateTemplate().update(user);
	}

	/**
	 * 根据id查找帐务帐号
	 */
	public User queryUser(Integer id) {
		return (User) this.getHibernateTemplate().find("from User u where u.id="+id).get(0);
	}
	
	/**
	 * 查找所有的帐务帐号
	 */
	public Collection<User> queryUsers() {
		List<User> users =this.getHibernateTemplate().find("from User u");
		return users;
	}
	
	/**
	 * 根据查询条件查找帐务帐号
	 */
	public Collection<User> queryUsers(String cond) {
		return this.getHibernateTemplate().find("from User u where 1=1 "+cond);
	}

	public Collection<User> queryUsers(int currentPage) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 根据当前页数和查询条件查找帐务帐号
	 */
	public Collection<User> queryUsers(String cond, int currentPage) {
		final String qryStr= cond;
		System.out.println("qryStr = "+qryStr);
		System.out.println("currentPage = "+currentPage);
		final int startRow =(currentPage-1)*PageParameter.CNT_EACH_PAGE;
		
		return this.getHibernateTemplate().executeFind(new HibernateCallback(){
			
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query=session.createQuery("from User u where 1=1 " + qryStr);
				query.setFirstResult(startRow);
				query.setMaxResults(PageParameter.CNT_EACH_PAGE);
				
				return query.list();
			}
			
		});
	}

	/**
	 * 查找帐务帐号的总数
	 */
	public int queryUserCnt() {
		Integer i = (Integer) this.getHibernateTemplate().find("select count(*) from User u where 1=1 ").get(0);
		return i;
	}

	/**
	 * 根据查询条件查找帐务帐号的总数
	 */
	public int queryUserCnt(String cond) {
		Integer i = (Integer) this.getHibernateTemplate().find("select count(*) from User u where 1=1 "+cond).get(0);
		return i;
	}

public User login(String userName, String password) {
	System.out.println(".....................");
		List<User> user = this.getHibernateTemplate().find("from User u where u.loginname=? and " +
				"u.loginpassword=? ",new Object[]{userName,password});
		if(user == null || user.size() == 0)
			return null;
		else
			return user.get(0);
		 
	}

public User queryUserByLoginname(Integer id) {
	List<User> user = this.getHibernateTemplate().find("from User u where u.id="+id);
	return user.get(0);
}

	

}
