package com.palmnest.dao.hibernate;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.dao.RoleDao;
import com.palmnest.model.Role;
import com.palmnest.model.RoleFunction;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;


/**
 * This class interacts with hibernate session to save/delete and
 * retrieve Role objects.
 *
 * @author <a href="mailto:chasel.java@gmail.com">Chasel Li</a>
 */
@Repository
public class RoleDaoHibernate extends GenericDaoHibernate<Role, Long> implements RoleDao {

	/**
	 * Constructor to create a Generics-based version using Role as the entity
	 */
	public RoleDaoHibernate() {
		super(Role.class);
	}

	/**
	 * {@inheritDoc}
	 */
	public Role getRoleByName(String rolename) {
		@SuppressWarnings("rawtypes")
		List roles = getSession().createCriteria(Role.class).add(Restrictions.eq("name", rolename)).list();
		if (roles.isEmpty()) {
			return null;
		} else {
			return (Role) roles.get(0);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void removeRole(String rolename) {
		Object  role    = getRoleByName(rolename);
		Session session = getSessionFactory().getCurrentSession();
		session.delete(role);
	}

	/*
	 * (non-Javadoc)
	 * @see com.palmnest.dao.RoleDao#queryRole(int, int)
	 */
	@Override
	public Pagenation<Role> queryRole(int pageNo, int pageSize, Map<String, String> criteria) {
		String strQueryHql = "from Role where isenalbed='1' ";
		String strCountHql = "select count(*) from Role where isenalbed='1' ";

		//非admin账号登录需要加过滤条件
		if (criteria.containsKey("orgStr") && StringUtils.isNotEmpty(criteria.get("orgStr").toString())) {
			strQueryHql = strQueryHql + " and orgId in (" + criteria.get("orgStr") + ") ";
			strCountHql = strCountHql + " and orgId in (" + criteria.get("orgStr") + ") ";
		}
		int        startIndex = (pageNo - 1) * pageSize;
		Long       totalCount = (Long) getSession().createQuery(strCountHql).uniqueResult();
		List<Role> list       = getSession().createQuery(strQueryHql).setFirstResult(startIndex).setMaxResults(pageSize).list();
		return new Pagenation<Role>(list, pageNo, totalCount.intValue(), pageSize);
	}

	@Override
	public List<RoleFunction> queryRoleFunctionSet(Role role) {
		String strHql = "from RoleFunction where role.id=" + role.getId();
		return getSession().createQuery(strHql).list();
	}

	@Override
	public void deleteRoleFunctions(long roleid) {
		String strSql = "delete from tr_app_role_function where roleid=" + roleid;
		getSession().createSQLQuery(strSql).executeUpdate();
	}

	@Override
	public void saveRoleFunction(RoleFunction model) {
		getSession().save(model);
	}

	/**
	 * 这个function 的意思 大概就是 查找包含某个功能的角色是什么
	 *
	 * @param sysCode TODO 4000 是什么鬼 这个是怎样定义的 查到了 4000 就是 电子放行条审核权限APP
	 * @param OrgId
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getRoleByOrgAndSysCode(String sysCode, Integer OrgId) {

		String sql = " SELECT t1.* " +
				" FROM tb_app_role t1 " +
				" LEFT JOIN tr_app_role_function t2 ON t1.ID = t2.ROLEID " +
				" LEFT JOIN tb_app_function t3 ON t2.FUNCTION_ID = t3.ID " +
				" WHERE " +
				" t1.ISENABLED = 1 " +
				" AND t3.SYSTEMCODE IN(" + sysCode + ") " +
				" and (t1.ROLE_TYPE=4 or t1.ROLE_TYPE=3 ) " +
				" and ( t1.ORG_ID = "+OrgId+" or  t1.ORG_ID =0) " ;
				
				//"AND t3.SYSTEMCODE IN(" + sysCode + ") " +
				//"and t1.ORG_ID = " + OrgId;

		return getJdbcTemplate().queryForList(sql);
	}

	@Override
	public List<Role> getRoleList(String type) {

		String strHQL = "from Role where isenalbed=?";

		if (StringUtils.isNotEmpty(type)) {
			strHQL = strHQL + " and id<>-1";
		}

		return getSession().createQuery(strHQL).setString(0, ElementConstant.YESORNO_1).list();
	}

	@Override
	public List<Role> getRoleListByOrg(String orgStr) {

		String strHQL = "SELECT * FROM tb_app_role WHERE id<>-1 AND ROLE_TYPE <> 3 AND ISENABLED='1' ";

		if (StringUtils.isNotBlank(orgStr)) {
			strHQL += "AND ORG_ID in (" + orgStr + ")";
		}

		return getSession().createSQLQuery(strHQL).addEntity(Role.class).list();
	}

	@Override
	public List<Role> getRoleListBySysCode(String id, String code) {
		String strHQL = "from Role where isenalbed='1' and SYSCODE='" + code + "' ";
		if (StringUtils.isNotEmpty(id)) {
			strHQL = strHQL + " and id<>" + id;
		}
		List<Role> list = getSession().createQuery(strHQL).list();
		return list;
	}

	@Override
	public List<Role> getByOrg(Integer orgId, Integer roleType) {
		String strHQL = "from Role where isenalbed='1' and orgId=" + orgId;
		if (roleType != null) {
			strHQL = strHQL + " and roleType =" + roleType;
		}
		return getSession().createQuery(strHQL).list();
	}

	@Override
	public void deleteRoleFunction(Long roleId, Integer functionId) {
		String strSql = "delete from tr_app_role_function where roleid=" + roleId + " and FUNCTION_ID=" + functionId;
		getSession().createSQLQuery(strSql).executeUpdate();

	}

	@Override
	public void deleteRoleFunctionByFuncId(Integer functionId) {
		String strSql = "delete from tr_app_role_function where FUNCTION_ID=" + functionId;
		getSession().createSQLQuery(strSql).executeUpdate();
	}

	/**
	 * 根据功能编码获取角色列表
	 *
	 * @param syscode
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getRoleListByFuncCode(String syscode, String userId) {
		StringBuilder sql = new StringBuilder("");
		sql.append(" select DISTINCT flr.id floorId,flr.name floorName ");
		sql.append(" from tb_app_function fuc ");
		sql.append(" left join tr_app_role_function rfuc on rfuc.FUNCTION_ID=fuc.id ");
		sql.append(" left join tb_app_role role on role.id=rfuc.roleid ");
		sql.append(" left join tr_app_user_role urle on urle.ROLE_ID=role.id ");
		sql.append(" left join tb_app_user u on u.id=urle.user_id ");
		sql.append(" left join tr_app_user_floor uf on (uf.user_id=u.id and uf.role_id=role.id) ");
		sql.append(" left join tb_floor flr on flr.id=uf.floor_id ");
		sql.append(" where u.isEnabled='1' and flr.isEnabled='1' and fuc.systemcode=" + syscode + " and u.id=" + userId + " ");

		return getJdbcTemplate().queryForList(sql.toString());
	}

	@Override
	public Role getVirAccountRole() {
		String strHQL = "from Role where isenalbed='1' and roleType=5 and SYSCODE='virAccountRole'";
		return (Role) getSession().createQuery(strHQL).list().get(0);
	}

	@Override
	public List<Map<String, Object>> getRoleByFunc(Integer orgId, String syscode) {
		StringBuilder sql=new StringBuilder("");
		sql.append(" SELECT DISTINCT  ");
		sql.append(" ar.id id,  ");
		sql.append(" ar. NAME name  ");
		sql.append(" FROM tb_app_function ap  ");
		sql.append(" JOIN tr_app_role_function arf ON ap.id = arf.function_id  ");
		sql.append(" JOIN tb_app_role ar ON arf.roleid = ar.id  ");
		sql.append(" WHERE ar.ISENABLED = 1  ");
		sql.append(" AND ap.systemcode = "+syscode);
		sql.append(" AND ( ar.ORG_ID = "+orgId+" OR ( ar.ROLE_TYPE >= 3 AND ar.ORG_ID = 0 ) ) ");
		return getJdbcTemplate().queryForList(sql.toString());
	}
}

