package com.qiankun.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.qiankun.dao.core.AbsDao;
import com.qiankun.dao.core.Hints;
import com.qiankun.entity.User;
import com.qiankun.pages.IPageList;
import com.qiankun.pages.PageListImpl;

@Repository
public class UserDaoImpl extends AbsDao<User, String> implements UserDao {
	
	private static final String FIND = "from User where ";
	
	private static final String FIND_USER_PAGE = " from User where (userId like ? or mobile like ?) ";
	
	private static final String FIND_LASTUSER_BY_GROUP = " from User where groups = ? order by createTime desc";
	
	private static final String LOGIN = " from User where mobile = ? and pwd = ? and isRemove=false";
	
	private static final String VALIDATE_MOBILE = " from User where mobile = ?";
	
	private static final String VALIDATE_TEAMNAME = " from User where teamName = ?";
	
	private static final String VALIDATE_PWD = " from User where id = ? and pwd = ? and isRemove=false";
	
	@Override
	public Boolean validateUserExistByMobile(String mobile) {
		Long count = findCount(" select count(*) " + VALIDATE_MOBILE, mobile);
		if (count > 0)
			return true;
		else
			return false;
	}
	
	@Override
	public Boolean validateUserExistByTeamName(String userName) {
		Long count = findCount(" select count(*) " + VALIDATE_TEAMNAME, userName);
		if (count > 0)
			return true;
		else
			return false;
	}
	
	@Override
	public User findLastUserByGroup(String groupId) {
		
		List<User> records = find(FIND_LASTUSER_BY_GROUP , new Hints(0,1),  groupId);
		if (records.size()>0) {
			return records.get(0);
		} else {
			return null;
		}
		
		
	}
	
	
	@Override
	public IPageList<User> findUserPage(String searchStr, String groupId, String order, String sort, Hints hints) {
		
		
		if (order == null){
			order = " createTime ";
		}
		if (sort == null){
			sort=" desc ";
		}
		
		String groupHql = null;
		if (groupId != null){
			groupHql = " and groups = ? ";
		}
		
		if (searchStr == null) {
			searchStr = "%";
		}
		String param = "%" + searchStr + "%";
		IPageList<User> users = new PageListImpl<User>();
		if (groupId != null){
			users.setRecords(find(FIND_USER_PAGE + groupHql + sortHQL(order, sort), hints, param, param, groupId));
			users.setRecordTotal(findCount(" select count(*) " + FIND_USER_PAGE + groupHql, param, param, groupId));
		} else {
			users.setRecords(find(FIND_USER_PAGE + sortHQL(order, sort), hints, param, param));
			users.setRecordTotal(findCount(" select count(*) " + FIND_USER_PAGE, param, param));
		}
		
		return users;
	}	
	
	
	@Override
	public User login(String mobile, String password) {
		return findUnique(LOGIN, new Hints(), mobile, password);
	}
	
	@Override
	public Boolean validatePwd(String id, String password) {
		Long count = findCount(" select count(*) " + VALIDATE_PWD, id, password);
		if (count > 0)
			return true;
		else
			return false;
		
	}
}
