package org.ccpit.base.user;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.transaction.Transactional;

import org.ccpit.base.controller.Convert;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageBo;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.role.Role;
import org.ccpit.base.role.RoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by sqp on 2015/9/5.
 */
@Repository
@Transactional
public class UserService {
	
	private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd MM:hh:ss");
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;

    public List<User> getAllUsers(){
        return userDao.queryAll();
    }
    
    public User getUserByLoginName(String loginName){
    	return userDao.getUserByLoginName(loginName);
    }
    
    public boolean addUser(User user){
        return userDao.save(user);
    }

    public boolean updateUser(User user){
        return userDao.update(user);
    }

    public boolean deleteUser(long id){
        return userDao.deleteById(id);
    }

    public Page<User> queryPage(PageRequest pr){
        Page<User> page = userDao.findPage(pr, "from " + User.class.getName(), new String[]{});
        return page;
    }
    
    public Page<User> queryPage(PageRequest pr,String hql){
        Page<User> page = userDao.findPage(pr, hql, new String[]{});
        return page;
    }
    public User getUser(long id){
        return userDao.queryById(id);
    }

    /**
     * 检查用户是否具有此角色 或者用户所在的组是否具有此角色
     *
     * @param user
     * @param role
     * @return
     */
    public boolean canUserOrInGroup(User user,Role role){
       return userDao.canUserOrInGroup(user, role);
    }

    /**
     * 获取一个用户的所有角色
     * @param user
     * @return
     */
    public Set<Role> getUserRoles(User user){
        User user1 = userDao.queryById(user.getId());
        return user1.getRoles();
    }
    /**
     * 获取一个用户所拥有的所有角色，包括用户所在的组拥有的角色
     * @param user
     * @return
     */
    public Set<Role> getUserRolesIncludeGroup(User user){
        return userDao.getUserRolesIncludeGroup(user);
    }

    public boolean saveUserRoles(User user,Long[] ids){
        Set<Role> roles = new HashSet<Role>();
        for (long id:ids){
            roles.add(roleDao.queryById(id));
        }
        return saveUserRoles(user, roles);
    }
    public boolean saveUserRoles(User user,Set<Role> roleSet){
        boolean success = false;
        try {
            user.getRoles().clear();
            boolean b = userDao.update(user);
            if(b){
            	User user1 = userDao.queryById(user.getId());
            	user1.setRoles(roleSet);
            	success = userDao.save(user1);
            }
        }catch (Exception e){
            success = false;
        }
        return success;
    }
    
    public Map<String,Object> convertToMap(User User){
        Map<String,Object> map = new HashMap<String, Object>();
        if (User==null){
        	return map;
        }
        Set<Role> roleSet =  User.getRoles();
        String roles = "";
        if(null != roleSet){
        	if(roleSet.size()>0){
        		for(Role role : roleSet){
        			roles += role.getRoleName()+",";
        		}
        		roles = roles.substring(0, roles.length()-1);
        	}
        }
        map.put("id",User.getId());
        map.put("createTime",null == User.getCreateTime()? "": sdf.format(User.getCreateTime()));
        map.put("creator", User.getCreator());
        map.put("username",User.getUsername());
        map.put("loginName",User.getLoginName());
        map.put("countStatus", 1 == User.getCountStatus()?"有效":"无效"); 
        map.put("loginCount", User.getLoginCount()); 
        map.put("company", User.getCompany());
        map.put("userType","back".equals(User.getUserType())?"后台用户":"非后台用户");
        map.put("roles", roles);
        return map;
    }

    public PageBo<User> convert(Page<User> page){
        return new PageBo<User>(page, new Convert<User>() {
            @Override
            public Map<String, Object> convert(User obj) {
                return convertToMap(obj);
            }
        });
    }

}
