package com.palmnest.dao.hibernate;

import com.palmnest.dao.AppMenuDao;
import com.palmnest.model.AppMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 系统菜单管理底层DAO实现
 *
 * @author yb
 * @since 2014-05-28
 */
@Slf4j
@Repository("appMenuDao")
public class AppMenuDaoHibernate extends GenericDaoHibernate<AppMenu, Integer> implements AppMenuDao {

	public AppMenuDaoHibernate() {
		super(AppMenu.class);
	}

	@Override
	public int menuTotalCount() {
		String strHql = "select count(*) from AppMenu";

		List<Long> counts = getSession().createQuery(strHql).list();

		if (counts != null && counts.size() > 0) {
			return counts.get(0).intValue();
		}

		return 0;
	}

	@Override
	public AppMenu getMenu(String treeCode, String parentCode) {

		String strHql = "from AppMenu where treeCode=? and parentCode=?";

		List<AppMenu> menus = getSession().createQuery(strHql).setString(0, treeCode).setString(1, parentCode).list();

		if (menus != null && menus.size() > 0) {
			return menus.get(0);
		}

		return null;
	}

	@Override
	public List<AppMenu> getAll2() {
		String strHql = "from AppMenu where isApp=0";
		return getSession().createQuery(strHql).list();
	}

	@Override
	public int maxMenuId() {

		String strHql = "select max(id) from AppMenu";

		Integer maxid = (Integer) getSession().createQuery(strHql).uniqueResult();

		if (maxid != null) {
			return maxid.intValue();
		}

		return 0;
	}

	@Override
	public void deleMenu(String treeCode, String parentCode) {

		String strSQL = "delete from tb_app_menu where TREECODE=? and PARENTCODE=?";

		int i = getSession().createSQLQuery(strSQL).setString(0, treeCode).setString(1, parentCode).executeUpdate();
		log.info("删除成功." + i);
	}

	@Override
	public List<AppMenu> getAllAppMenu() {
		String        strHql = "from AppMenu where isApp = 1 order by ordernum";
		List<AppMenu> menus  = getSession().createQuery(strHql).list();
		return menus;
	}

	@Override
	public List<AppMenu> getMenuByParent(String parentCode) {
		//isApp = 1 and
		String strHql = "from AppMenu where parentCode=? order by ordernum ";

		List<AppMenu> menus = getSession().createQuery(strHql).setString(0, parentCode).list();

		return menus;
	}

	@Override
	public List<AppMenu> getMenuByFunid(String funIds) {
		String        sql  = "select * from tb_app_menu where FUNCTION_ID in (" + funIds + ")";
		List<AppMenu> list = getSession().createSQLQuery(sql).addEntity(AppMenu.class).list();
		return list;
	}

	@Override
	public List<AppMenu> getLevelOneMenu() {
		String        sql  = "select * from tb_app_menu where PARENTCODE=0";
		List<AppMenu> list = getSession().createSQLQuery(sql).addEntity(AppMenu.class).list();
		return list;
	}

}
