package com.qiankun.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

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

@Repository
public class RainbowPlanUserDaoImpl extends AbsDao<RainbowPlanUser,String> implements RainbowPlanUserDao {
	
	private static final String FIND_USER_PAGE = " from RainbowPlanUser where (phone like ? or disease like ? or name like ? or nickName like ?)    ";
	
    @Override
    public RainbowPlanUser findByOpenid(String openid) {
        return findUnique("from RainbowPlanUser where openid=?",new Hints(),openid);
    }

    @Transactional
    @Override
    public RainbowPlanUser save(RainbowPlanUser entity) {
        return super.save(entity);
    }

    @Transactional
    @Override
    public void update(RainbowPlanUser entity) {
        super.update(entity);
    }

    @Override
    public RainbowPlanUser findByPhone(String phone) {
        return findUnique("from RainbowPlanUser where phone = ?",new Hints(),phone);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<RainbowPlanUser> findByIds(List<String> ids) {
        Query query = getSessionFactory().getCurrentSession().createQuery("from RainbowPlanUser where id in (:ids)").setParameterList("ids",ids);
        return query.list();
    }

    @Override
    public boolean validateUserExistByPhone(String phone) {
        Long count = findCount(" select count(*) from RainbowPlanUser where phone = ?" , phone);
        if (count > 0){
            return true;
        }else {
            return false;
        }
    }
    
    @Override
	public IPageList<RainbowPlanUser> findUserPage(String searchStr, Integer type, Integer status, String order, String sort, Hints hints) {
		
		
		if (order == null){
			order = " createTime ";
		}
		if (sort == null){
			sort=" desc ";
		}
		
		String hql = "";
		if (type != null){
			hql = " and type = " + type ;
		}
		
		if (status != null){
			hql = " and status = " + status ;
		}
		
		if (searchStr == null) {
			searchStr = "%";
		}
		String param = "%" + searchStr + "%";
		IPageList<RainbowPlanUser> users = new PageListImpl<RainbowPlanUser>();
		
		users.setRecords(find(FIND_USER_PAGE + hql + sortHQL(order, sort), hints, param, param, param, param));
		users.setRecordTotal(findCount(" select count(*) " + FIND_USER_PAGE + hql, param, param, param, param));
		
		
		return users;
	}
}
