/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:project
 * File Name:OrgDao.java
 * Package Name:ccpit.base.orgManage
 * Date:2015年9月18日下午4:59:13
 * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
 *
 */

package org.ccpit.base.orgManage;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.ccpit.base.dao.BaseDao;
import org.ccpit.base.role.Role;
import org.ccpit.base.user.User;
import org.springframework.stereotype.Repository;

/**
 * ClassName:OrgDao <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2015年9月18日 下午4:59:13 <br/>
 * 
 * @author dingwei
 * @version
 * @since JDK 1.6
 * @see
 */
@Repository
public class OrgDao extends BaseDao<OrgInfo> {

	public List<OrgInfo> getChildOrgById(long id) {
		String hql = "from " + OrgInfo.class.getName()+" where parentId=" + id;
		List<OrgInfo> orgList = super.query(hql, null);
		return orgList;
	}
	
	 /**
     * 查询用户所在的部门
     *
     * @param user
     * @return
     */
    public List<OrgInfo> getUserGroupsByUser(User user) {
        return query("select distinct ug from " + OrgInfo.class.getName() + " as ug left join ug.users as u " +
                "where u.id=? ", user.getId());
    }

    /**
     * 查询所有拥有此角色的部门
     *
     * @param role
     * @return
     */
    public List<OrgInfo> getUserGroupsByRole(Role role) {
        return query("select distinct ug from " + OrgInfo.class.getName() + " as ug left join ug.roles as r " +
                "where r.id=? ", role.getId());
    }


    /**
     * 用户所在的部门是否具有role的角色
     *
     * @param user
     * @param role
     * @return
     */
    public boolean canUserInGroup(User user, Role role) {
        List<OrgInfo> userGroups = getUserGroupsByUser(user);
        Set<Role> roleSet = new HashSet<Role>();
        for (OrgInfo userGroup : userGroups) {
            roleSet.addAll(userGroup.getRoles());
        }
        return roleSet.contains(role);
    }

    /**
     * 获取用户所在部门的所有角色
     * @param user
     * @return
     */
    public Set<Role> getRolesForUser(User user){
        List<OrgInfo> groups = getUserGroupsByUser(user);
        Set<Role> roles = new HashSet<Role>();
        for (OrgInfo userGroup:groups){
            roles.addAll(userGroup.getRoles());
        }
        return roles;
    }
}