package com.itjob.service;

import java.text.SimpleDateFormat;
import java.util.*;

import com.itjob.dao.BaseDao;
import com.itjob.dao.model.TRight;
import com.itjob.dao.model.Role;
/**
 * 角色信息管理的业务逻辑实现类.
 */
public class RoleManagerImpl implements RoleManager {
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private BaseDao dao;

	public void setDao(BaseDao dao) {
		this.dao = dao;
	}
	
	/**
	 * 获得角色信息列表
	 */
	public List getRoleList() throws Exception {
		List<Map> returnList = new ArrayList<Map>();
		List list = dao.hqlQuery("from Role");
		Role role = null;
		Map<String, String> map = null;
		for (int i = 0; i < list.size(); i++) {
			map = new HashMap<String, String>();
			role = (Role) list.get(i);
			map.put("num", String.valueOf(i + 1));
			map.put("trId", String.valueOf(role.getTrId()));
			map.put("roleName", role.getRoleName());
			map.put("description", role.getDescription());
			map.put("createTime", sdf.format(role.getCreateTime()));
			returnList.add(map);
		}
		return returnList;
	}
	
	/**
	 * 保存角色信息
	 * @param role 角色信息对象
	 */
	public void saveRole(Role role) throws Exception {
		role.setCreateTime(new Date());
		dao.saveObject(role);
	}
	
	/**
	 * 根据主键ID获得角色信息
	 * @param 角色的主键ID
	 */
	public Role getRole(long trId) throws Exception {
		Role role = (Role) dao.getObject(Role.class, trId);
		return role;
	}
	
	/**
	 * 更新角色信息
	 * @param role 角色信息对象
	 */
	public void updateRole(Role role) throws Exception {
		Role rolePo = (Role) dao.getObject(Role.class, role.getTrId());
		rolePo.setRoleName(role.getRoleName());
		rolePo.setDescription(role.getDescription());
		dao.updateObject(rolePo);
	}
	
	/**
	 * 删除一到多个角色信息
	 * @param idArray 角色ID数组
	 */
	public void deleteRole(String[] idArray) throws Exception {
		Role role = null;
		for (int i = 0; i < idArray.length; i++) {
			role = (Role) dao.getObject(Role.class, Long.parseLong(idArray[i]));
			dao.deleteObject(role);
		}
	}

	/**
	 * 更新角色的权限集合
	 * @param roleId 角色id
	 * @param rightIds 权限ID数组
	 */
	public void updateRoleRight(long trId, String rightIds) throws Exception {
		Set<TRight> rights = new HashSet<TRight>(0);
		String[]  rightIdArray = rightIds.split(",");
		TRight right = null;
		Role role = (Role) dao.getObject(Role.class, trId);
		for (int i = 0; i < rightIdArray.length; i++) {
			right = (TRight) dao.getObject(TRight.class, Long.parseLong(rightIdArray[i]));
			rights.add(right);
		}
		role.setRights(rights);
		dao.updateObject(role);
	}
}
