/**
 * Copyright &copy; 2013-2017 <a href="http://www.rhcncpa.com/">瑞华会计师事务所</a> All rights reserved.
 */
package com.jeeplus.modules.sys.utils;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.BaseService;
import com.jeeplus.common.sms.SMSUtils;
import com.jeeplus.common.utils.*;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.activityassignment.dao.ActivityAssignmentDao;
import com.jeeplus.modules.activityassignment.entity.ActivityAssignment;
import com.jeeplus.modules.sys.dao.*;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.jeeplus.modules.sysparameter.dao.SysParameterDao;
import com.jeeplus.modules.sysparameter.dao.SysParameterValueDao;
import com.jeeplus.modules.sysparameter.entity.SysParameter;
import com.jeeplus.modules.sysparameter.entity.SysParameterValue;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcessUser;
import com.jeeplus.modules.workjobgrade.entity.WorkJobGrade;
import com.jeeplus.modules.workjobgrade.service.WorkJobGradeService;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.dao.WorkStaffBasicInfoDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.java_websocket.WebSocket;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 用户工具类
 * @author jeeplus
 * @version 2013-12-05
 */
public class UserUtils {

	private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
	private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
	private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
	private static AreaDao areaDao = SpringContextHolder.getBean(AreaDao.class);
	private static WorkActivityProcessDao processDao = SpringContextHolder.getBean(WorkActivityProcessDao.class);
	private static OfficeDao officeDao = SpringContextHolder.getBean(OfficeDao.class);
	private static SysRoleActivityDao roleActivityDao = SpringContextHolder.getBean(SysRoleActivityDao.class);
	private static ActivityAssignmentDao activityAssignmentDao = SpringContextHolder.getBean(ActivityAssignmentDao.class);
	private static WorkJobGradeService workJobGradeService = SpringContextHolder.getBean(WorkJobGradeService.class);
	private static SysParameterValueDao sysParameterValueDao = SpringContextHolder.getBean(SysParameterValueDao.class);
	private static SysParameterDao sysParameterDao = SpringContextHolder.getBean(SysParameterDao.class);
	private static WorkStaffAchivesDao workStaffAchivesDao = SpringContextHolder.getBean(WorkStaffAchivesDao.class);
	private static WorkStaffBasicInfoDao workStaffBasicInfoDao = SpringContextHolder.getBean(WorkStaffBasicInfoDao.class);

	public static final String USER_CACHE = "userCache";
	public static final String USER_CACHE_ID_BRANCHOFFICE = "branchoffice_id_";
	public static final String USER_CACHE_ID_ = "id_";
	public static final String USER_CACHE_LOGIN_NAME_ = "ln";
	public static final String USER_CACHE_LOGIN_NAME_BRANCHOFFICE = "branchoffice_ln";
	public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";
	public static final String USER_CACHE_COM_ID_ = "cid_";
	public static final String USER_CACHE_COM_ID_BRANCHOFFICE = "branchoffice_cid_";

	public static final String CACHE_ROLE_LIST = "roleList";
	public static final String CACHE_COMPANY = "company_";
	public static final String CACHE_MENU_LIST = "menuList";
	public static final String CACHE_AREA_LIST = "areaList";
	public static final String CACHE_OFFICE_LIST = "officeList";
	public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";
	public static final String CACHE_SELECT_ROLE = "selectRole";

	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static User get(String id){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
		if (user ==  null){
			user = userDao.get(id);
			if (user == null){
				return null;
			}
			List<Role> roleList = roleDao.findList(new Role(user));
			user.setRoleList(roleList);
			CacheUtils.remove(USER_CACHE);
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_COM_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static User getByCompanyAndUserId(String id,String companyId){
		User user = userDao.getByCompanyAndUserId(id,companyId);
		return user;
	}

	public static User getNoSession(String id){
		User user = userDao.get(id);
		if (user == null){
			return null;
		}
		List<Role> roleList = roleDao.findList(new Role(user));
		user.setRoleList(roleList);
		CacheUtils.remove(USER_CACHE);
		CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
		CacheUtils.put(USER_CACHE, USER_CACHE_COM_ID_ + user.getId(), user);
		CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		return user;
	}

	/**
	 * 用户获取岗位
	 * @param id
	 * @return
	 */
	public static User getByUserId(String id){
		User user = userDao.getByUserId(id);
		if (user == null){
			return null;
		}
		Role role = new Role(user);
		user.setRoleList(roleDao.findList(role));
		return user;
	}

	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	public static User getByLoginName(String loginName){
		//UserUtils.clearCache();
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
		if (user == null){
			User user1 = new User();
			Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
			if(loginName.length()==18){
               WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoDao.findByCard(loginName);
               if(workStaffBasicInfo == null){
               	  return null;
			   }
               String loginName1 = workStaffBasicInfo.getMobile();
				user1.setLoginName(loginName1);
				user = userDao.getByLoginName(user1);
			} else if(pattern.matcher(loginName).matches() || loginName.contains("admin")){
				user1.setLoginName(loginName);
				user = userDao.getByLoginName(user1);
			}else {
				user1.setName(loginName);
				List<User> list = userDao.getByName(user1);
//				if(list != null && list.size()>1){
//					throw new AuthenticationException("msg:"+loginName+"存在重名.");
//				}
				if(list != null && list.size()>0){
				   user = list.get(0);
				}
			}
			if (user == null){
				return null;
			}
			List<Role> roleList = roleDao.findList(new Role(user));
			user.setRoleList(roleList);
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_COM_ID_ + user.getComId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}

	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	public static User getByLoginNameNoSesion(String loginName){
//		User user = userDao.getByLoginName(new User(null, loginName));
////		if (user == null){
////			return null;
////		}
		User user = new User();
		User user1 = new User();
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		if(loginName.length()==18){
			WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoDao.findByCard(loginName);
			if(workStaffBasicInfo == null){
				return null;
			}
			String loginName1 = workStaffBasicInfo.getMobile();
			user1.setLoginName(loginName1);
			user = userDao.getByLoginName(user1);
		}else if(pattern.matcher(loginName).matches() || loginName.equals("admin")){
			user1.setLoginName(loginName);
			user = userDao.getByLoginName(user1);
		}else {
			user1.setName(loginName);
			List<User> list = userDao.getByName(user1);
			if(list != null && list.size()>0){
				user = list.get(0);
			}
		}
		if (user == null){
			return null;
		}
		List<Role> roleList = roleDao.findList(new Role(user));
		user.setRoleList(roleList);
		CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
		CacheUtils.put(USER_CACHE, USER_CACHE_COM_ID_ + user.getComId(), user);
		CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		return user;
	}

	/**
	 * 清除当前用户缓存
	 */
	public static void clearCache(){
		removeCache(CACHE_ROLE_LIST);
		removeCache(CACHE_MENU_LIST);
		removeCache(CACHE_AREA_LIST);
		removeCache(CACHE_OFFICE_LIST);
		removeCache(CACHE_OFFICE_ALL_LIST);
		removeCache(CACHE_SELECT_ROLE);
		clearCache(getUser());
	}

	/**
	 * 清除指定用户缓存
	 * @param user
	 */
	public static void clearCache(User user){
		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getOldLoginName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_COM_ID_ + user.getComId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_BRANCHOFFICE + user.getId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_BRANCHOFFICE + user.getLoginName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_BRANCHOFFICE + user.getOldLoginName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_COM_ID_BRANCHOFFICE + user.getComId());
		CacheUtils.remove(USER_CACHE, CACHE_COMPANY + user.getComId());
		if (user.getOffice() != null && user.getOffice().getId() != null){
			CacheUtils.remove(USER_CACHE, USER_CACHE_LIST_BY_OFFICE_ID_ + user.getOffice().getId());
		}
	}

	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static User getUser(){
		Principal principal = getPrincipal();
		if (principal!=null){
			User user = get(principal.getId());
			if (user != null){
				return user;
			}
			return new User();
		}

		// 如果没有登录，则返回实例化空的User对象。
		return new User();
	}

	/**
	 * 获取用户所有企业
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Office> getAllCompany(User user){
		List<Office> companyList = new ArrayList<Office>();
		Role role1 = new Role();
		role1.setUser(user);
		List<Role> roleList = roleDao.findList(new Role(user));
		user.setRoleList(roleList);
		Set<Office> set = new  HashSet<Office>();
		for (Role role : roleList) {
			if(role.getId() != null && role.getCompany() != null && "1".equals(role.getCompany().getUseable())){
				if (set.add(role.getCompany())){
					companyList.add(role.getCompany());
				}
			}
		}
		return companyList;
	}



	/**
	 * 获取当前（非管理员）用户岗位
	 * @return
	 */
	public static List<Role> getSelectRole(){
		List<Role> roles = (List<Role>)getCache("selectRole");
		if (roles != null && roles.size()==1 && roles.get(0).getId().equals("1c54e003c1fc4dcd9b087ef8d48abac3")){
			Role role = roles.get(0);
			role.setEnname("system");
			roles.add(role);
			return roles;
		}else if (roles != null && roles.size()!= 0) {
			return roles;
		}else {
			Role role = new Role();
			role.setCompany(getUser().getCompany());
			role.setUser(getUser());
			List<Role> roleList = roleDao.findList(role);
			if(roleList!=null && roleList.size()!=0) {
				UserUtils.putCache("selectRole", roleList);
				return roleList;
			}else {
				return null;
			}
		}
	}

	/**
	 * 获取当前（非管理员）用户岗位
	 * @return
	 */
	public static int getSelectRoleMax(){
		// 0 无权限 1 仅限查看本人数据 2 仅限查看当前用户所在部门数据 3 仅限查看当前分公司数据 4 查看当前公司数据 5查看所有数据
		List<Role> roles = getSelectRole();
		int count = 0;
		if (roles!=null && roles.size()!=0){
			for (Role role : roles){
				if (role.getDataScope().equals("1")){
					count = 5;
					break;
				}else if (role.getDataScope().equals("2")){
					if(count<5){
						count = 4;
					}
				}else if (role.getDataScope().equals("5")){
					if (count<4) {
						count = 3;
					}
				}else if (role.getDataScope().equals("4")){
					if (count<3) {
						count = 2;
					}
				}else if (role.getDataScope().equals("8")){
					if (count<2) {
						count = 1;
					}
				}
			}
		}
		return count;
	}

	/**
	 * 获取当前（非管理员）用户岗位
	 * @return
	 */
	public static Boolean getSelectRoleInfo(){
		List<Role> roles = (List<Role>)getCache("selectRole");
		if (roles == null || roles.size()== 0) {
			roles = getSelectRole();
		}else if (roles.size()==1 && roles.get(0).getId().equals("1c54e003c1fc4dcd9b087ef8d48abac3")){
			return true;
		}
		if (roles!=null && roles.size()>0) {
			for (Role role : roles) {
				if (role.getDataScope().equals("2")) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 获取当前（非管理员）用户岗位
	 * @return
	 */
	public static List<Role> getRolesByMenu(User user, String menuId){
		List<Role> roles = roleDao.getRolesByMenu(user.getId(),menuId,user.getCompany().getId());
		return roles;
	}

	/**
	 * 获取当前（非管理员）用户企业
	 * @return
	 */
	public static Office getSelectCompany(){
		List<Role> roles = (List<Role>)getCache("selectRole");
		if (roles != null && roles.size()!= 0) {
			for (Role role:roles){
				if (role == null) {
					if(role.getDataScope().equals("1") && role.getEnname().equals("system")){
						return new Office("1");
					}
				}
			}
		}
		Object companyId = getCache("selectCompany");
		if(companyId.equals("1")){
			User user = userDao.get("1");
			companyId = user.getComId();
		}
		if (companyId != null) {
			Office company = (Office)CacheUtils.get(USER_CACHE, CACHE_COMPANY + companyId);
			if (company == null) {
				company = officeDao.get(companyId.toString());
				CacheUtils.put(USER_CACHE, CACHE_COMPANY + companyId, company);
			}
			return company;
		}else {
			Office company = (Office)CacheUtils.get(USER_CACHE, CACHE_COMPANY + getUser().getComId());
			try {
				if (company == null) {
					User user = getUser();
					company = officeDao.get(user.getComId());
					if (StringUtils.isNotBlank(user.getComId())) {
						putCache("selectCompany", user.getComId());
					}
					if ((user.getOffice() != null) && (StringUtils.isNotBlank(user.getOffice().getId()))) {
						putCache("selectOffice", user.getOffice().getId());
					}
					CacheUtils.put(USER_CACHE, CACHE_COMPANY + companyId, company);
				}
			}catch (Exception e){
				System.out.println("getSelectCompany Exception e:"+e);
			}

			return company;
		}
	}
	/**
	 * 保存当前（非管理员）用户公司部门
	 * @return
	 */
	@Transactional(readOnly = false)
	public static void saveSelectCompany() {
		User user=getUser();
		Object companyId = getCache("selectCompany");
		Object officeId = getCache("selectOffice");
		//List<Role> roles = (List<Role>)getCache("selectRole");
		if (companyId != null) {
			user.setComId(companyId.toString());
			user.setCompany(new Office(companyId.toString()));
		}
		if (officeId != null) {
			user.setOffice(new Office(officeId.toString()));
		}
		/*if (roles != null && roles.size()!=0) {
			user.setRole(new Role(roleId.toString()));
		}*/
		user.preUpdate();
		userDao.updateUserInfo(user);
	}

	/**
	 * 获取当前（非管理员）用户部门
	 * @return
	 */
	public static Office getSelectOffice(){
		/*List<Role> roles = (List<Role>)getCache("selectRole");
		if (roles != null && roles.size()!=0) {
			Role role = roleDao.get(roleId.toString());
			if(role.getDataScope() =="1" && role.getEnname()=="system"){
				return null;
			}
		}*/
		Object officeId = getCache("selectOffice");
		Office office = new Office();
		if (officeId != null) {
			office = officeDao.get(officeId.toString());

		}else {
			office = officeDao.get(getUser().getOffice().getId());
		}
		return office;
	}
	/**
	 * 获取当前（非管理员）用户部门
	 * @return
	 */
	public static Office getOfficeById(String officeId){
		Office office = officeDao.get(officeId);
		return office;
	}

	/**
	 * 获取当前用户所有岗位列表
	 * @return
	 */
	public static List<Role> getRoleList(User user){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
		if (roleList == null){
			if (user.isAdmin()){
				roleList = roleDao.findAllList(new Role());
			}else{
				Role role = new Role();
				role.setUser(user);
				roleList = roleDao.findList(role);
			}
			putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}

	/**
	 * 获取当前用户在当前企业是否是管理员
	 *
	 * @return
	 */
	public static boolean isManager(){
		List<Role> roles = (List<Role>)getCache("selectRole");
		if(roles == null || roles.size() ==0){
			User user = UserUtils.getUser();
			List<Role> roleList = UserUtils.getRoleListByCompany(user.getId());
			roles = roleList;
		}
		int count = 0;
		for (Role role:roles){
			if(UserUtils.getUser().isAdmin() || (org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && (role.getEnname().endsWith("gly")||role.getEnname().equals("system")))){
				count++;
			}
		}
		if (count==0){
			return false;
		}else {
			return true;
		}
	}
	/**
	 * 获取当前用户所有岗位列表
	 * @return
	 */
	public static List<Role> getRoleList(){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
		if (roleList == null){
			User user = get(getUser().getId());
			if (user.isAdmin()){
				roleList = roleDao.findAllList(new Role());
			}else{
				Role role = new Role();
				role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u","",MenuStatusEnum.ROLE.getValue()));
				roleList = roleDao.findList(role);
			}
			putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}

	/**
	 * 获取当前用户所有岗位列表
	 * @return
	 */
	public static List<Role> getRoleListByCompany(Role role){
		List<Role>roleList = roleDao.findList(role);
		return roleList;
	}

	public static List<Role> getRoleListByCompanys(Role role){
		List<Role>roleList = roleDao.getRoleListByCompanys(role);
		return roleList;
	}
	/**
	 * 获取当前用户所有岗位列表
	 * @return
	 */
	public static List<SysRoleActivity> getRoleActivityListByCompany(SysRoleActivity roleActivity){
		List<SysRoleActivity>roleList = roleActivityDao.findList(roleActivity);
		return roleList;
	}

	/**
	 * 获取当前用户所有岗位列表
	 * @return
	 */
	public static String getRoleActivityEnname(String companyId,User user){
		SysRoleActivity roleActivity = new SysRoleActivity();
		/*User u = get(user.getId());
		Office branchCompany = u.getBranchOffice();
		if (branchCompany != null && StringUtils.isNotBlank(branchCompany.getId())) {
			roleActivity.setBranchCompanyId(branchCompany.getId());
		}*/
		roleActivity.setCompanyId(companyId);
		List<SysRoleActivity> roleList = roleActivityDao.findListByCompany(roleActivity);
		if (roleList!=null && roleList.size()!=0){
			return DateUtils.getByEnnme(roleList.get(0).getEnname()).toString();
		}else {
			Office company = UserUtils.getSelectCompany();
			String enname = StringUtils.getPinYinHeadChar(company.getName(), 2)+System.currentTimeMillis();
			return enname;
		}
	}
	/**
	 * 获取当前用户所有岗位列表
	 * @return
	 */
	public static String getRoleActivity(String companyId){
		SysRoleActivity roleActivity = new SysRoleActivity();
		roleActivity.setCompanyId(companyId);
		List<SysRoleActivity> roleList = roleActivityDao.findListByCompany(roleActivity);
		if (roleList!=null && roleList.size()!=0){
			return DateUtils.getByEnnme(roleList.get(0).getEnname()).toString();
		}else {
			Office company = UserUtils.getSelectCompany();
			String enname = StringUtils.getPinYinHeadChar(company.getName(), 2)+System.currentTimeMillis();
			return enname;
		}
	}
	/**
	 * 获取当前用户所有岗位列表
	 * @return
	 */
	public static String setRoleActivityEnname(String companyId,String name,int type){
		SysRoleActivity roleActivity = new SysRoleActivity();
		roleActivity.setCompanyId(companyId);
		List<SysRoleActivity> roleList = roleActivityDao.findList(roleActivity);
		String enname = "";
		if (roleList!=null && roleList.size()!=0){
			enname = roleList.get(0).getEnname();
		}else {
			Office company = UserUtils.getSelectCompany();
			enname = StringUtils.getPinYinHeadChar(company.getName(), 2)+System.currentTimeMillis();
		}
		StringBuffer buffer = DateUtils.getByEnnme(enname);
		if (type==1){
			buffer.append(name);
		}else {
			buffer.append(StringUtils.getPinYinHeadChar(name,1));
		}

		return buffer.toString();
	}

	/**
	 * 获取当前用户企业岗位列表
	 * @return
	 */
	public static List<Role> getRoleListByCompany(String userId){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
		if (roleList == null){
			User user = getUser();
			if(user == null || user.getId() ==null ){
				user =get(userId);
			}
			if (user.isAdmin()){
				roleList = roleDao.findAllList(new Role());
			}else{
				Role role = new Role();
				//role.getSqlMap().put("dsf", BaseService.dataScopeFilter2(user.getCurrentUser(), "o", "u"));
				role.setCompany(user.getCompany());
				role.setUser(user);
				roleList = roleDao.findList(role);
			}
			putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}

	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static List<Menu> getMenuList(){
		@SuppressWarnings("unchecked")
		List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
		if (menuList == null || menuList.size()==0){

			List<Role> selectRole = (List<Role>)getCache(CACHE_SELECT_ROLE);
			User user = getUser();
			if (user.isAdmin()){
				menuList = menuDao.findAllList(new Menu());
			}else{
				Menu m = new Menu();
				if(null!=selectRole&&selectRole.size()>0){
					System.out.println("select role ");
					m.setUserId(user.getId());
					List<String> roleList = new ArrayList<>(selectRole.size());
					for (Role role:selectRole){
						roleList.add(role.getId());
					}
					m.setRoleList(roleList);
					menuList = menuDao.findByUserRole(m);
				}else{
					System.out.println("no select role ");
					m.setUserId(user.getId());
					menuList = menuDao.findByUserId(m);
				}
			}
			putCache(CACHE_MENU_LIST, menuList);
		}
		if (menuList==null || menuList.size()==0){
			Menu menu = new Menu();
			menu.setId("1");
			menuList.add(menu);
		}
		return menuList;
	}

	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static List<Menu> getMenuList(Role role){
		List<Menu> menuList = new ArrayList<>();
		User user = getUser();
		Menu m = new Menu();
		if(null!=role){
			System.out.println("select office role ");
			//m.setUserId(user.getId());
			m.setRoleId(role.getId());
			ArrayList<String> roleIds = new ArrayList<>();
			roleIds.add(role.getId());
			m.setRoleList(roleIds);
			menuList = menuDao.findByUserRole(m);
		}else{
			System.out.println("no select office role ");
			m.setUserId(user.getId());
			menuList = menuDao.findByUserId(m);
		}
		return menuList;
	}

	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static Menu getTopMenu(){
		Menu topMenu = new Menu();
		try {
			topMenu =  getMenuList().get(0);
		}catch (Exception e){
			List<Menu> menuList = new ArrayList<>();
			if (getMenuList()==null || getMenuList().size()==0){
				Menu menu = new Menu();
				menu.setId("1");
				menuList.add(menu);
			}else {
				menuList = getMenuList();
			}
			topMenu = menuList.get(0);
		}
		return topMenu;
	}
	/**
	 * 获取当前用户授权的区域
	 * @return
	 */
	public static List<Area> getAreaList(){
		@SuppressWarnings("unchecked")
		List<Area> areaList = (List<Area>)getCache(CACHE_AREA_LIST);
		if (areaList == null){
			areaList = areaDao.findAllList(new Area());
			putCache(CACHE_AREA_LIST, areaList);
		}
		return areaList;
	}

	/**
	 * 获取当前用户有权限访问的部门
	 * @return
	 */
	public static List<Office> getOfficeList(){
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_LIST);
		if (officeList == null){
			User user = get(getUser().getId());
			if (user.isAdmin()){
				officeList = officeDao.findAllList(new Office());
			}else{
				Office office = new Office();
				office.getSqlMap().put("dsf", BaseService.dataScopeFilterOR(user, "a", MenuStatusEnum.OFFICE.getValue()));
				office.setUseable("1");
				Office company = UserUtils.getSelectCompany();
				office.setIsSon(company.getIsSon());
				office.setParentIds(company.getId());
				officeList = officeDao.findList(office);
			}
			putCache(CACHE_OFFICE_LIST, officeList);
		}
		return officeList;
	}

	/**
	 * 获取当前用户有权限访问的部门
	 * @return
	 */
	public static List<Office> getOfficeAllList(){
		@SuppressWarnings("unchecked")
		List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_ALL_LIST);
		if (officeList == null){
			officeList = officeDao.findAllList(new Office());
		}
		return officeList;
	}

	/**
	 * 获取当前用户当前公司所有的部门
	 * @return
	 */
	public static List<Office> getOfficeAllList(Office office){
		List<Office> officeList = officeDao.findAllList(office);
		return officeList;
	}

	public static List<Office> getAllOfficeList(){
		String comId = UserUtils.getUser().getComId();
		List<Office> officeList = officeDao.findAllList1(comId);
		return officeList;
	}

	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}

	/**
	 * 获取当前登录者对象
	 */
	public static Principal getPrincipal(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			if (principal != null){
				return principal;
			}
//			subject.logout();
		}catch (UnavailableSecurityManagerException e) {

		}catch (InvalidSessionException e){

		}
		return null;
	}

	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
//			subject.logout();
		}catch (InvalidSessionException e){

		}
		return null;
	}

	// ============== User Cache ==============

	public static Object getCache(String key) {
		return getCache(key, null);
	}

	public static Object getCache(String key, Object defaultValue) {
//		Object obj = getCacheMap().get(key);
		Object obj = getSession().getAttribute(key);
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
//		getCacheMap().remove(key);
		getSession().removeAttribute(key);
	}

	public static String getTime(Date date){
		StringBuffer time = new StringBuffer();
		Date date2 = new Date();
		long temp = date2.getTime() - date.getTime();
		long days = temp / 1000 / 3600/24;                //相差小时数
		if(days>0){
			time.append(days+"天");
		}
		long temp1 = temp % (1000 * 3600*24);
		long hours = temp1 / 1000 / 3600;                //相差小时数
		if(days>0 || hours>0){
			time.append(hours+"小时");
		}
		long temp2 = temp1 % (1000 * 3600);
		long mins = temp2 / 1000 / 60;                    //相差分钟数
		time.append(mins + "分钟");
		return  time.toString();
	}


	//发送注册码
	public static String sendRandomCode(String mobile, String randomCode) throws IOException {
		//发送内容
		String content = "【匞匞】您的验证码是："+randomCode+"，有效期30分钟，请在有效期内使用。";

		return SMSUtils.send(mobile, content,"","0");

	}

	//容联云通讯
	public static HashMap<String,Object> sendRandomCodes(String mobile, String randomCode) throws IOException {
		return SMSUtils.sends(mobile, randomCode);

	}

	//注册用户重置密码
	public static String sendPass(String uid, String pwd, String tel, String password) throws IOException {
		//发送内容
		String content = "您的新密码是："+password+"，请登录系统，重新设置密码。";
		return SMSUtils.send(tel, content,"","0");

	}

	//发送预警信息
	public static String sendWarning(String mobile, String warningContent) throws IOException {
		//发送内容
		String content = "【匞匞】系统预警通知："+warningContent;

		return SMSUtils.send(mobile, content,"","0");

	}
	/**
	 * 导出Excel调用,根据姓名转换为ID
	 */
	public static User getByUserName(String name){
		User u = new User();
		u.setName(name);
		List<User> list = userDao.findList(u);
		if(list.size()>0){
			return list.get(0);
		}else{
			return new User();
		}
	}
	/**
	 * 导出Excel使用，根据名字转换为id
	 */
	public static Office getByOfficeName(String name){
	    if(StringUtils.isBlank(name)){
	        return null;
        }
		Office o = new Office();
		o.setName(name);
		User user = UserUtils.getUser();
		Office branchOffice = user.getBranchOffice();
		if(!user.getCompany().equals(branchOffice)){
			o.setBranchOffice(branchOffice.getId());
		}
		o.setParentIds(user.getCompany().getId());
		List<Office> list = officeDao.findByName(o);
		if(list.size()>0){
			return list.get(0);
		}else{
		    o.setTopCompany(name);
            list = officeDao.findByTopCompany(o);
			return (list!=null&&list.size()>0)?list.get(0):null;
		}
	}

	/**
	 * 导出财务格式
	 * @param
	 * @return
	 */
	public static String getDecimalFormat(BigDecimal money) {
		DecimalFormat df = new DecimalFormat("#,#00.00");
		String str = df.format(money);
		return str;
	}

	/**
	 * 导出Excel使用，根据名字转换为id
	 */
//	public static Area getByAreaName(String name){
//		Area a = new Area();
//		a.setName(name);
//		List<Area> list = areaDao.findList(a);
//		if(list.size()>0){
//			return list.get(0);
//		}else{
//			return new Area();
//		}
//	}
	public static Area getByAreaName(String name){
		Area area = areaDao.getByAreaName(name);
		return area;
	}
	public static String checkRole(String id, String comId) {
		List<Role> roleList = roleDao.checkRole(id,comId);
		String roleName = "";
		if (roleList!=null && roleList.size()!=0){
			for (Role role:roleList){
				roleName += role.getName()+",";
			}
		}
		if (StringUtils.isNotBlank(roleName)){
			roleName = roleName.substring(0,roleName.length()-1);
		}
		return  roleName;
	}
	public static String checkRoleByOffice(String id, String comId) {
		List<Role> roleList = roleDao.checkRole(id,comId);
		String roleName = "";
		if (roleList!=null && roleList.size()!=0){
			roleName = roleList.get(0).getName();
		}
		return  roleName;
	}

	public static String getpingyin(int s){
		String str="";
		for(int i=0;i<s;i++){//你想生成几个字符的，就把3改成几，如果改成１,那就生成一个随机字母．
			str= str+(char) (Math.random ()*26+'a');
		}
		System.out.println(str);
		return  str;
	}

	public static List<SysRoleActivity> getByRole(Role role){
		List<SysRoleActivity> sysRoleActivities = roleActivityDao.getByRole(role.getId());
		return sysRoleActivities;
	}

	/**
	 * 根据ID获取用户
	 * @param
	 * @return 取不到返回null
	 */
	public static Office getByCompany(String officeId){
		Office office = officeDao.get(officeId);
		String parentIds = office.getParentIds();
		if (StringUtils.isNotBlank(parentIds)) {
			System.out.println("parentIds=" + parentIds);
			String[] ids = parentIds.split(",");
			for (int i = ids.length - 1; i > 0; i--) {
				Office o = officeDao.get(ids[i]);
				if (o.getType().equals("3")) {
					return o;
				}else if (office.getType().equals("1")){
					return o;
				}
			}
		}
		return getSelectCompany();
	}

	public static List<User> getByRoleActivityEnname(String enname,int type,String officeId,String businessType,User userId){
		//businessType 1:全平台   2:合同模块 	3:合同归档 	4:项目登记 	5:开票管理
		// 6:退票管理 	7:收入管理 	8:报销管理 	9:月度计划管理 10:案例管理 11:行政管理 12 报告管理13 采购合同管理 14采购管理  15报废管理
		//16借用管理  17 领用管理 18劳动关系管理 19 加班申请 20 出差申请 21外勤申请 22 转正申请 23 职级调整 24 部门调整 25 请假申请
		//26 补卡申请 27 考勤审批
		String name = getRoleActivityEnname(UserUtils.getSelectCompany().getId(),userId);
		if (!enname.contains(name)){
			enname = name+enname;
		}
		Role role = new Role();
		role.setEnname(enname);
		Office office = officeDao.get(officeId);
		if (StringUtils.isNotBlank(office.getBranchOffice()) || type == 2) {
			if (type == 2) {
				role.setOffice(new Office(officeId));
			} else if (type == 3) {
				role.setBranchCompany(new Office(office.getBranchOffice()));
			} else if(type == 1){
				Office branchOffice =  officeDao.get(office.getBranchOffice());
				if (StringUtils.isNotBlank(branchOffice.getParentId())&& !"0".equals(branchOffice.getParentId())){
					Office topCompany = officeDao.get(branchOffice.getParentId());
					if ("1".equals(topCompany.getType())){
						Office office1 = new Office();
						office1.setName("总公司");
						role.setBranchCompany(office1);
					}else{
						role.setBranchCompany(new Office(branchOffice.getParentId()));
					}
				}else {
					Office office1 = new Office();
					office1.setName("总公司");
					role.setBranchCompany(office1);
				}
			} else {
				Office office1 = new Office();
				office1.setName("总公司");
				role.setBranchCompany(office1);
			}
		}else {
			Office office1 = new Office();
			office1.setName("总公司");
			role.setBranchCompany(office1);
		}
		String roleIds = "";
		List<Role> roles = roleDao.getByRoleActivityEnname(role);
		for (Role r : roles) {
			roleIds += r.getId() + ",";
		}
		User user = new User();
		user.setRoleIds(roleIds);
		List<User> list = userDao.findListByRoleList(user);
		List<User> users = new ArrayList<>();
		Set<String> set = new HashSet<>();
		for (User u:list){
			ActivityAssignment select = new ActivityAssignment();
			select.setCreateBy(u);
			select.setStartDate(new Date());
			select.setType(businessType);
			select.setCompanyId(getSelectCompany().getId());
			ActivityAssignment activityAssignment = activityAssignmentDao.getByUserIdAndDate(select);
			if (activityAssignment!=null && !activityAssignment.getIsNewRecord()){
				User activityAssignmentUser = activityAssignment.getUser();
				activityAssignmentUser.setRemarks(u.getName()+"的委托任务");
				if (!set.contains(activityAssignmentUser.getId())) {
					users.add(activityAssignmentUser);
				}
			}else {
				if (!set.contains(u.getId())) {
					users.add(u);
				}
			}
			set.add(u.getId());
		}
		//暂时删除
		/*if(users==null || users.size()==0){
			users = null;
		}*/
		return users;
	}

	public static List<User> getByRoleActivityEnname(String enname,int type,String officeId,String companyId,String businessType){
		//businessType 1:全平台   2:合同模块 	3:合同归档 	4:项目登记 	5:开票管理
		// 6:退票管理 	7:收入管理 	8:报销管理 	9:月度计划管理 10:案例管理 11:行政管理 12 报告管理13 采购合同管理 14采购管理  15报废管理
		//16借用管理  17 领用管理 18劳动关系管理 19 加班申请 20 出差申请 21外勤申请 22 转正申请 23 职级调整 24 部门调整 25 请假申请
		//26 补卡申请 27 考勤审批 28 单笔工资项发放
		String name = getRoleActivityEnname(companyId,new User());
		if (!enname.contains(name)){
			enname = name+enname;
		}
		Role role = new Role();
		role.setEnname(enname);
		Office office = officeDao.get(officeId);
		if (StringUtils.isNotBlank(office.getBranchOffice()) || type == 2) {
			if (type == 2) {
				role.setOffice(new Office(officeId));
			} else if (type == 3) {
				role.setBranchCompany(new Office(office.getBranchOffice()));
			} else if(type == 1){
				Office branchOffice =  officeDao.get(office.getBranchOffice());
				if (StringUtils.isNotBlank(branchOffice.getParentId())&& !"0".equals(branchOffice.getParentId())){
					Office topCompany = officeDao.get(branchOffice.getParentId());
					if ("1".equals(topCompany.getType())){
						Office office1 = new Office();
						office1.setName("总公司");
						role.setBranchCompany(office1);
					}else{
						role.setBranchCompany(new Office(branchOffice.getParentId()));
					}
				}else {
					Office office1 = new Office();
					office1.setName("总公司");
					role.setBranchCompany(office1);
				}
			} else {
				Office office1 = new Office();
				office1.setName("总公司");
				role.setBranchCompany(office1);
			}
		}else {
			Office office1 = new Office();
			office1.setName("总公司");
			role.setBranchCompany(office1);
		}
		String roleIds = "";
		List<Role> roles = roleDao.getByRoleActivityEnname(role);
		for (Role r : roles) {
			roleIds += r.getId() + ",";
		}
		User user = new User();
		user.setRoleIds(roleIds);
		List<User> list = userDao.findListByRoleList(user);
		List<User> users = new ArrayList<>();
		Set<String> set = new HashSet<>();
		for (User u:list){
			ActivityAssignment select = new ActivityAssignment();
			select.setCreateBy(u);
			select.setStartDate(new Date());
			select.setType(businessType);
			select.setCompanyId(companyId);
			ActivityAssignment activityAssignment = activityAssignmentDao.getByUserIdAndDate(select);
			if (activityAssignment!=null && !activityAssignment.getIsNewRecord()){
				User activityAssignmentUser = activityAssignment.getUser();
				activityAssignmentUser.setRemarks(u.getName()+"的委托任务");
				if (!set.contains(activityAssignmentUser.getId())) {
					users.add(activityAssignmentUser);
				}
			}else {
				if (!set.contains(u.getId())) {
					users.add(u);
				}
			}
			set.add(u.getId());
		}
		//暂时删除
		/*if(users==null || users.size()==0){
			users = null;
		}*/
		return users;
	}

	public static List<User> getByRoleActivityEnnames(String enname,String officeId,String businessType,User userId){
		//businessType 1:全平台   2:合同模块 	3:合同归档 	4:项目登记 	5:开票管理
		// 6:退票管理 	7:收入管理 	8:报销管理 	9:月度计划管理 10：案例管理 11:行政管理 12 报告管理13 采购合同管理 14采购管理  15报废管理  16借用管理  17 领用管理 18劳动关系管理
		String name = getRoleActivityEnname(UserUtils.getSelectCompany().getId(),userId);
		if (!enname.contains(name)){
			enname = name+enname;
		}
		Role role = new Role();
		role.setEnname(enname);
		role.setCompany(UserUtils.getSelectCompany());
		//根据别名找角色
		SysRoleActivity selectRole = roleActivityDao.getByEnname(enname);
		Set<String> set = new HashSet<>();
		Office office = officeDao.get(officeId);
		if (StringUtils.isNotBlank(office.getBranchOffice()) || (selectRole != null && StringUtils.isNotBlank(selectRole.getType()) && selectRole.getType().equals("2"))) {
			if (selectRole != null && StringUtils.isNotBlank(selectRole.getType())) {
				if (selectRole.getType().equals("2")) {
					role.setOffice(new Office(officeId));
				} else if (selectRole.getType().equals("3")) {
					role.setBranchCompany(new Office(office.getBranchOffice()));
				} else if(selectRole.getType().equals("1")){
					Office branchOffice =  officeDao.get(office.getBranchOffice());
					if (StringUtils.isNotBlank(branchOffice.getParentId()) && !"0".equals(branchOffice.getParentId())){
						Office topCompany = officeDao.get(branchOffice.getParentId());
						if ("1".equals(topCompany.getType())){
							Office office1 = new Office();
							office1.setName("总公司");
							role.setBranchCompany(office1);
						}else{
							role.setBranchCompany(new Office(branchOffice.getParentId()));
						}
					}else {
						Office office1 = new Office();
						office1.setName("总公司");
						role.setBranchCompany(office1);
					}
				} else {
					Office office1 = new Office();
					office1.setName("总公司");
					role.setBranchCompany(office1);
				}
			}
		}else {
			Office office1 = new Office();
			office1.setName("总公司");
			role.setBranchCompany(office1);
		}

		List<Role> roles = roleDao.getByRoleActivityEnname(role);

		String roleIds = "";
		for (Role r:roles){
			roleIds += r.getId()+",";
		}
		User user = new User();
		user.setRoleIds(roleIds);
		List<User> list = userDao.findListByRoleList(user);
		List<User> users = new ArrayList<>();
		for (User u:list){
			ActivityAssignment select = new ActivityAssignment();
			select.setCreateBy(u);
			select.setStartDate(new Date());
			select.setType(businessType);
			select.setCompanyId(getSelectCompany().getId());
			ActivityAssignment activityAssignment = activityAssignmentDao.getByUserIdAndDate(select);
			if (activityAssignment!=null && !activityAssignment.getIsNewRecord()){
				User activityAssignmentUser = activityAssignment.getUser();
				activityAssignmentUser.setRemarks(u.getName()+"的委托任务");
				if (!set.contains(activityAssignmentUser.getId())) {
					users.add(activityAssignmentUser);
				}
			}else {
				if (!set.contains(u.getId())) {
					users.add(u);
				}
			}
			set.add(u.getId());
		}
		/*if(users==null || users.size()==0){
			users = null;
		}*/
		return users;
	}


	public static List<User> getByProssType(String processId,int count){
		WorkActivityProcess workActivityProcess = new WorkActivityProcess();
		workActivityProcess.setProcessInstanceId(processId);
		workActivityProcess.setCount(count);
		workActivityProcess.setType("1");
		List<WorkActivityProcess> processList = processDao.findByProcInsIdAudit(workActivityProcess);
		List<User> userList = new ArrayList<>();
		if (processList!=null && processList.size()!=0){
			WorkActivityProcess process = processList.get(0);
			if (process!=null && process.getProcessUserList()!=null && process.getProcessUserList().size()!=0){
				for (WorkActivityProcessUser workActivityProcessUser:process.getProcessUserList()){
					User user = new User();
					user.setId(workActivityProcessUser.getId());
					user.setName(workActivityProcessUser.getName());
					userList.add(user);
				}
			}
		}
		if(userList==null || userList.size()==0){
			userList = null;
		}
		return userList;
	}


	public static String getNumber(String number){
		try {
			if (number.length()!=3){
				return "001";
			}else {
				Integer num = Integer.parseInt(number);
				if (num<9){
					return "00"+(num+1);
				}else if (num == 9){
					return "010";
				}else if (num < 99){
					return "0"+(num+1);
				}else if (num == 99){
					return "100";
				}else {
					return (num+1)+"";
				}
			}
		}catch (Exception e){
			System.out.println("getNumber Exception e"+e);
		}
		return "001";
	}

	public static void pushIm(String alias,String content){
		//User user = UserUtils.getUser();
		//SmackUtils.sendSmackMessage(alias,content,"sys");
		/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(alias);
		for (WebSocket toUserConn:toUserConns) {
			String message = "{\"to\":\""+alias+"\"," +
					"\"msg\":\"审批信息 "+content+"\"," +
					"\"useType\":\"sys\"}";
			ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
		}*/
	}
	public static void pushMeIm(String alias){
		//SmackUtils.sendSmackMessage(alias,"","sys_me");
		/*SmackUtils.sendSmackMessage(alias,"",true);
		List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(alias);
		for (WebSocket toUserConn:toUserConns) {
			String message = "{\"useType\":\"sys_me\"}";
			ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
		}*/
	}
	public static void pushIm(List<String> alias,String content){
		for (String alia:alias){
			//SmackUtils.sendSmackMessage(alia,content,"sys");
		}
		/*for (String userId:alias){
			List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(userId);
			for (WebSocket toUserConn:toUserConns) {
				String message = "{\"to\":\""+alias+"\"," +
						"\"msg\":\"审批信息 "+content+"\"," +
						"\"useType\":\"sys\"}";
				ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
			}
		}*/
	}

	public static Office getBranchOfficeById(String branchOffice) {
		return officeDao.get(branchOffice);
	}

	public static void pushInfoToApp(String title,String content,Map<String,Object> extras,String aliases){
		if (extras.get("appShow")==null){
			extras.put("appShow","0");
		}

		JPushClientUtil.sendNotificationToAlias(title, content, extras, aliases);
	}

	public static WorkJobGrade getByWorkJobGradeName(String s) {
		List<WorkJobGrade> workJobGradeList = workJobGradeService.findByName(s);
		if(workJobGradeList==null||workJobGradeList.size()<=0){
			return new WorkJobGrade();
		}
		return workJobGradeList.get(0);
	}
	//系统自动发起申请用
	public static List<User> getByRoleActivityEnnameTask(String enname,int type,String officeId,String businessType,User userId){
		//businessType 1:全平台   2:合同模块 	3:合同归档 	4:项目登记 	5:开票管理
		// 6:退票管理 	7:收入管理 	8:报销管理 	9:月度计划管理 10:案例管理 11:行政管理 12 报告管理13 采购合同管理 14采购管理  15报废管理
		//16借用管理  17 领用管理 18劳动关系管理 19 加班申请 20 出差申请 21外勤申请 22 转正申请 23 职级调整 24 部门调整 25 请假申请
		String name = getRoleActivityEnnameTask(userId.getCompany().getId(),userId);
		if (!enname.contains(name)){
			enname = name+enname;
		}
		Role role = new Role();
		role.setEnname(enname);
		Office office = officeDao.get(officeId);
		if (StringUtils.isNotBlank(office.getBranchOffice()) || type == 2) {
			if (type == 2) {
				role.setOffice(new Office(officeId));
			} else if (type == 3) {
				role.setBranchCompany(new Office(office.getBranchOffice()));
			} else if(type == 1){
				Office branchOffice =  officeDao.get(office.getBranchOffice());
				if (StringUtils.isNotBlank(branchOffice.getParentId())&& !"0".equals(branchOffice.getParentId())){
					Office topCompany = officeDao.get(branchOffice.getParentId());
					if ("1".equals(topCompany.getType())){
						Office office1 = new Office();
						office1.setName("总公司");
						role.setBranchCompany(office1);
					}else{
						role.setBranchCompany(new Office(branchOffice.getParentId()));
					}
				}else {
					Office office1 = new Office();
					office1.setName("总公司");
					role.setBranchCompany(office1);
				}
			} else {
				Office office1 = new Office();
				office1.setName("总公司");
				role.setBranchCompany(office1);
			}
		}else {
			Office office1 = new Office();
			office1.setName("总公司");
			role.setBranchCompany(office1);
		}
		String roleIds = "";
		List<Role> roles = roleDao.getByRoleActivityEnname(role);
		for (Role r : roles) {
			roleIds += r.getId() + ",";
		}
		User user = new User();
		user.setRoleIds(roleIds);
		List<User> list = userDao.findListByRoleList(user);
		List<User> users = new ArrayList<>();
		Set<String> set = new HashSet<>();
		for (User u:list){
			ActivityAssignment select = new ActivityAssignment();
			select.setCreateBy(u);
			select.setStartDate(new Date());
			select.setType(businessType);
			select.setCompanyId(userId.getCompany().getId());
			ActivityAssignment activityAssignment = activityAssignmentDao.getByUserIdAndDate(select);
			if (activityAssignment!=null && !activityAssignment.getIsNewRecord()){
				User activityAssignmentUser = activityAssignment.getUser();
				activityAssignmentUser.setRemarks(u.getName()+"的委托任务");
				if (!set.contains(activityAssignmentUser.getId())) {
					users.add(activityAssignmentUser);
				}
			}else {
				if (!set.contains(u.getId())) {
					users.add(u);
				}
			}
			set.add(u.getId());
		}
		//暂时删除
		/*if(users==null || users.size()==0){
			users = null;
		}*/
		return users;
	}
   //系统自动发起申请用
	public static String getRoleActivityEnnameTask(String companyId,User user){
		SysRoleActivity roleActivity = new SysRoleActivity();
		User u = get(user.getId());
		Office branchCompany = u.getBranchOffice();
		if (branchCompany != null && StringUtils.isNotBlank(branchCompany.getId())) {
			roleActivity.setBranchCompanyId(branchCompany.getId());
		}
		roleActivity.setCompanyId(companyId);
		List<SysRoleActivity> roleList = roleActivityDao.findListByCompany(roleActivity);
		if (roleList!=null && roleList.size()!=0){
			return DateUtils.getByEnnme(roleList.get(0).getEnname()).toString();
		}else {
			Office company = user.getCompany();
			String enname = StringUtils.getPinYinHeadChar(company.getName(), 2)+System.currentTimeMillis();
			return enname;
		}
	}

	/**
	 * 获取系统参数
	 * parameter 参数类型
	 * branchOffice 分公司Id 分公司id为空传公司id
	 * @return
	 */
	public static String getSysParam(String parameter,User user) {
		Office office = officeDao.get(user.getOffice().getId());
		SysParameter SysParameter=sysParameterDao.findIsforce(parameter);
		if(office!=null&&SysParameter!=null&&"1".equals(SysParameter.getIsForce())){//公司必须自己定义参数
			if (StringUtils.isNotBlank(office.getBranchOffice())) {//分公司的人
				SysParameterValue sysParameterValue = sysParameterValueDao.findValueByParameter(parameter, office.getBranchOffice());
				if (sysParameterValue != null) {
					return sysParameterValue.getValue();
				}else{
					return "";
				}
			}else{
				SysParameterValue sysComValue = sysParameterValueDao.findValueByParameter(parameter, user.getCompany().getId());
				if (sysComValue != null) {
					return sysComValue.getValue();
				} else {
					return "";
				}
			}
		}else{
			if (office!=null&&StringUtils.isNotBlank(office.getBranchOffice())) {//分公司的人
				SysParameterValue sysParameterValue = sysParameterValueDao.findValueByParameter(parameter, office.getBranchOffice());
				if (sysParameterValue == null) {
					SysParameterValue sysComValue = sysParameterValueDao.findValueByParameter(parameter, user.getCompany().getId());
					if (sysComValue == null) {
						SysParameterValue sysValue = sysParameterValueDao.findSysValue(parameter);
						return sysValue.getValue();
					} else {
						return sysComValue.getValue();
					}
				} else {
					return sysParameterValue.getValue();
				}
			}else{
				SysParameterValue sysComValue = sysParameterValueDao.findValueByParameter(parameter, user.getCompany().getId());
				if (sysComValue == null) {
					SysParameterValue sysValue = sysParameterValueDao.findSysValue(parameter);
					return sysValue.getValue();
				} else {
					return sysComValue.getValue();
				}
			}
		}
	}

	/**
	 * 获取系统参数
	 * parameter 参数类型
	 * branchOffice 分公司Id 分公司id为空传公司id
	 * @return
	 */
	public static String getSysParamByCompany(String parameter,String companyId) {
		SysParameter SysParameter=sysParameterDao.findIsforce(parameter);
		if(SysParameter!=null&&"1".equals(SysParameter.getIsForce())){//公司必须自己定义参数
			SysParameterValue sysComValue = sysParameterValueDao.findValueByParameter(parameter,companyId);
			if (sysComValue != null) {
				return sysComValue.getValue();
			} else {
				return "";
			}
		}else{
			SysParameterValue sysComValue = sysParameterValueDao.findValueByParameter(parameter, companyId);
			if (sysComValue == null) {
				SysParameterValue sysValue = sysParameterValueDao.findSysValue(parameter);
				return sysValue.getValue();
			} else {
				return sysComValue.getValue();
			}
		}
	}


	/**
	 * 获取当前用户在当前企业是否是管理员
	 *
	 * @return
	 */
	public static String managerType(){
		List<Role> roles = (List<Role>)getCache("selectRole");
		if(roles == null || roles.size() ==0){
			User user = UserUtils.getUser();
			List<Role> roleList = UserUtils.getRoleListByCompany(user.getId());
			roles = roleList;
		}
		Boolean falt = false;
		Boolean falt1 = false;
		String companyId="";
		String branchCompany="";
		for (Role role:roles){
			if((org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && ("gly".equals(role.getEnname())))){
				companyId=role.getCompany().getId();
				falt=true;
				break;
			}
		}
		if(falt){
			return companyId;
		}else{
			for (Role role:roles){
				if((org.apache.commons.lang3.StringUtils.isNotBlank(role.getEnname()) && (role.getEnname().endsWith("fgly")))){
					branchCompany=role.getBranchCompany().getId();
					falt1=true;
					break;
				}
			}
			if(falt1){
				return branchCompany;
			}
		}
		return "";
	}

	/**
	 * 获取当前用户分公司Id如果是总公司人员存公司Id
	 * @return
	 */
	public static String getSelectBranchOffice(){
		Office office=officeDao.get(UserUtils.getSelectOffice().getId());
		if(StringUtils.isNotBlank(office.getBranchOffice())){
			return office.getBranchOffice();
		}else{
			return UserUtils.getSelectCompany().getId();
		}
	}
	public static WorkStaffBasicInfo getBasicInfo() {
		WorkStaffBasicInfo w = new WorkStaffBasicInfo();
		w.setUserId(UserUtils.getUser().getId());
		w.setCompany(UserUtils.getSelectCompany());
		WorkStaffBasicInfo workStaffBasicInfo = workStaffAchivesDao.getBasicInfo(w);
		return workStaffBasicInfo;
	}

	/**
	 * 获取当前用户所有管理员岗位列表
	 * @return
	 */
	public static List<Role> getManagerRoleList(User user){
		@SuppressWarnings("unchecked")
		List<Role> roleList =  roleDao.getManagerRoleList(user.getId(),UserUtils.getSelectCompany().getId());
		return roleList;
	}

    public static List<String> findBranchOfficeId(Office branchCompany) {
	    if(branchCompany==null||StringUtils.isBlank(branchCompany.getId())){
	        return null;
        }
	    if(StringUtils.isBlank(branchCompany.getBranchOffice())){
	        return officeDao.findBranchOfficeId(null,branchCompany.getId());
        }
        return officeDao.findBranchOfficeId(branchCompany.getId(),null);
    }

    public static List<String> findChildOfficeId(Office office) {
        return officeDao.findChildOfficeId(office.getId());
    }

	/**
	 * 获取人事主任
	 */
	public static List<User> findRszrList(User user){
		String comId = user.getComId();
		Role rsbzr = new Role();
		Office office = new Office();
		office.setId(comId);
		rsbzr.setEnname("rsbzr");
		rsbzr.setCompany(office);
		Role role = roleDao.getByEnname(rsbzr);
		List<User> users = userDao.findUserByRoleId(role.getId(), comId);
		return users;
	}
}
