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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.bos.BOSClientUtil;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.ossutil.OssClient;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.security.Digests;
import com.jeeplus.common.security.shiro.session.JedisSessionDAO;
import com.jeeplus.common.security.shiro.session.SessionDAO;
import com.jeeplus.common.service.BaseService;
import com.jeeplus.common.utils.*;
import com.jeeplus.modules.modules.dao.ModuleChooseDao;
import com.jeeplus.modules.modules.entity.ModuleChoose;
import com.jeeplus.modules.sys.dao.*;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.security.SystemAuthorizingRealm;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.LogUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.tools.utils.TwoDimensionCode;
import com.jeeplus.modules.utils.ErrorCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * 系统管理，安全相关实体的管理类,包括用户、岗位、菜单.
 *
 * @author jeeplus
 * @version 2013-12-05
 */
@Service
@Transactional(readOnly = true)
public class SystemService extends BaseService implements InitializingBean {

    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;
    private String sessionKeyPrefix = Global.getConfig("redis.keyPrefix") + "_session_";
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private SysRoleActivityDao roleActivityDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private OfficeDao officeDao;
    @Autowired
    private SessionDAO sessionDao;
    @Autowired
    private ModuleChooseDao moduleChooseDao;
    @Autowired
    private UserofficeService userofficeService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private DictService dictService;
    public SessionDAO getSessionDao() {
        return sessionDao;
    }

    // -- User Service --//

    /**
     * 获取岗位
     *
     * @param user
     * @return
     */
    public List<Role> getRoleListByUser(User user,Office company) {
        Role role = new Role();
        role.setCompany(company);
        role.setUser(user);
        List<Role> roleList = roleDao.findList(role);
        return roleList;
    }

    /**
     * 获取用户
     *
     * @param id
     * @return
     */
    public User getUser(String id) {
        return UserUtils.get(id);
    }


    /**
     * 根据登录名获取用户
     *
     * @param loginName
     * @return
     */
    public User getUserByLoginName(String loginName) {
        return UserUtils.getByLoginName(loginName);
    }

    public Page<User> findUser(Page<User> page, User user) {
        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
        user.getSqlMap().put("dsf",
                dataScopeFilter(user.getCurrentUser(), "o", "a","s",MenuStatusEnum.USER.getValue()));
        // 设置分页参数
        user.setPage(page);
        if (user.getOffice()!=null&&StringUtils.isNotBlank(user.getOffice().getId())) {
            Office office = officeService.get(user.getOffice().getId());
            if (office!=null&&"1".equals(office.getType())) {
                user.setCompany(office);
                user.setOffice(null);
            }
        }
        // 执行分页查询
        if (user.getCompany() == null || StringUtils.isBlank(user.getCompany().getId())){
            user.setCompany(UserUtils.getSelectCompany());
        }
        List<User> users = userDao.findList(user);
       /* if (users!=null && users.size()!=0){
            for (User u :users){
                if (u.getBranchOffice()!=null && StringUtils.isNotBlank(u.getBranchOffice().getId())){
                    Office branchOffice = officeService.get(u.getBranchOffice().getId());
                    u.setBranchOffice(branchOffice);
                }
            }
        }*/
        page.setList(users);
        return page;
    }
    public Page<User> findUserByCompany(Page<User> page, User user) {
        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
        user.getSqlMap().put("dsf",
                dataScopeFilter(user.getCurrentUser(), "o", "a","s", MenuStatusEnum.USER.getValue()));
        // 设置分页参数
        user.setPage(page);
        if (user.getOffice()!=null&&StringUtils.isNotBlank(user.getOffice().getId())) {
            Office office = officeService.get(user.getOffice().getId());
            if (office!=null&&"1".equals(office.getType())) {
                user.setCompany(office);
                user.setOffice(null);
            }
        }
        // 执行分页查询
        if (user.getCompany() == null || StringUtils.isBlank(user.getCompany().getId())){
            user.setCompany(UserUtils.getSelectCompany());
        }
        List<User> users = userDao.findListByComany(user);
       /* if (users!=null && users.size()!=0){
            for (User u :users){
                if (u.getBranchOffice()!=null && StringUtils.isNotBlank(u.getBranchOffice().getId())){
                    Office branchOffice = officeService.get(u.getBranchOffice().getId());
                    u.setBranchOffice(branchOffice);
                }
            }
        }*/
        page.setList(users);
        return page;
    }
    public Page<User> findUserByRoleOffice(Page<User> page, User user) {

        user.setPage(page);
        // 执行分页查询
        if(!UserUtils.getUser().isAdmin()){
            // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
            user.getSqlMap().put("dsf",
                    dataScopeFilter(user.getCurrentUser(), "o", "a","s", MenuStatusEnum.USER.getValue()));
            // 设置分页参数
            if (user.getCompany() == null || StringUtils.isBlank(user.getCompany().getId())){
                user.setCompany(UserUtils.getSelectCompany());
            }
        }
        page.setList(userDao.findList(user));
        return page;
    }

    public Page<User> findUser2(Page<User> page, User user) {
        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
        user.getSqlMap().put("dsf",
                dataScopeFilter(user.getCurrentUser(), "o", "a","s", MenuStatusEnum.USER.getValue()));
        // 设置分页参数
        user.setPage(page);
        // 执行分页查询
        if (user.getCompany() == null || StringUtils.isBlank(user.getCompany().getId())){
            user.setCompany(UserUtils.getSelectCompany());
        }
        List<User> ulist= userDao.findList(user);
        List<User> ulist1 = new ArrayList<User>();
        for (User u:
                ulist) {
            if (u.isAdmin()){
                List<Role> roleList = roleDao.findAllList(new Role());
                u.setRoleList(roleList);
            }else{
                Role role = new Role();
                role.setUser(u);
                List<Role> roleList = roleDao.findList(role);
                u.setRoleList(roleList);
            }
            ulist1.add(u);
        }
        page.setList(ulist1);
        return page;
    }

    /**
     * 无分页查询人员列表
     *
     * @param user
     * @return
     */
    public List<User> findUser(User user) {
        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
        if(!UserUtils.getUser().isAdmin()){
            user.getSqlMap().put("dsf",
                    dataScopeFilter(user.getCurrentUser(), "o", "a","s", MenuStatusEnum.USER.getValue()));
            if (user.getCompany() == null || StringUtils.isBlank(user.getCompany().getId())){
                user.setCompany(UserUtils.getSelectCompany());
            }
        }
        List<User> list = userDao.findList(user);
        return list;
    }

    /**
     * 根据别名查询岗位
     *
     * @param role
     * @return
     */
    /*public Role getByEnname(Role role) {
        try {
            List<Role> roleList = roleDao.getByOffice(role);
            if (role.getOffice()!=null && StringUtils.isNotBlank(role.getOffice().getId())){
                return roleList.get(0);
            }else {

            }
            return role;
        }catch (Exception e){
            return null;
        }

    }*/

    /**
     * 通过部门ID获取用户列表，仅返回用户id和name（树查询用户时用）
     *
     * @return
     */
    public List<User> findUserByOfficeId(String officeId) {

        User user = new User();
        user.setOffice(new Office(officeId));
        if(!UserUtils.getSelectCompany().getId().equals("1")) {
            user.setCompany(UserUtils.getSelectCompany());
        }
        List<User> list = userDao.findUserByOfficeId(user);
        CacheUtils.put(UserUtils.USER_CACHE,
                UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + officeId, list);
        return list;
    }
    /**
     * 通过部门ID获取用户列表，仅返回用户id和name（树查询用户时用）
     *
     * @return
     */
    public List<User> findUserByOffices(Office office,Office company) {

        User user = new User();
        user.setOffice(office);
        user.setCompany(company);
        List<User> list = userDao.findUserByOffices(user);
        return list;
    }

    /**
     * 通过部门ID获取用户列表，仅返回用户id和name（树查询用户时用）
     * @return
     */
    public List<User> findUserByCompanyId(String companyId) {
        User user = new User();
        user.setCompany(new Office(companyId));
        List<User> userLists = new ArrayList<>();
        Set<String> set = new HashSet<>();
        user.setCompany(new Office(companyId));
        List<User> list = userDao.findUserByOfficeId(user);
        for (User users : list){
            set.add(users.getId());
        }
        List<Office> officeList = officeDao.findAllListByParentIds(new Office(companyId));
        for (Office office : officeList){
            User u = new User();
            u.setCompany(office);
            List<User> userList = userDao.findUserByOfficeId(u);
            for (User users : userList){
                set.add(users.getId());
            }
        }
        for (String id:set){
            userLists.add(UserUtils.get(id));
        }
        return userLists;
    }

    @Transactional(readOnly = false)
    public User saveUserInfo(User user) {
        if (StringUtils.isBlank(user.getId())) {
            user.preInsert();
            userDao.insert(user);
        } else {
            // 清除原用户机构用户缓存
            User oldUser = userDao.get(user.getId());
            if (oldUser.getOffice() != null
                    && oldUser.getOffice().getId() != null) {
                CacheUtils.remove(UserUtils.USER_CACHE,
                        UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_
                                + oldUser.getOffice().getId());
                CacheUtils.remove(UserUtils.USER_CACHE,
                        UserUtils.CACHE_COMPANY
                                + oldUser.getComId());
            }
            // 更新用户数据
            user.preUpdate();
            userDao.update(user);
        }
        ModuleChoose mc=new ModuleChoose();
        mc.setUser(user);
        StringBuffer moduleIds =new StringBuffer();
        Dict dict = new Dict();
        dict.setType("module_choose");
        List<Dict> list = dictService.findList(dict);
        if(list.size()>0){
            for (Dict dict2 : list) {
                moduleIds.append(dict2.getValue()+",");
            }
        }
        mc.setModuleId(moduleIds.toString());
        mc.preInsert();
        moduleChooseDao.insert(mc);
        if(StringUtils.isNotBlank(user.getId())){
            UserUtils.clearCache(user);
            removeSession(user);
        }
        return user;
    }



    @Transactional(readOnly = false)
    public AjaxJson registerUser(String mobile,String randomCode,String name,String password,String contextPath,String urls) {
        AjaxJson j = new AjaxJson();
        long time = System.currentTimeMillis();
        User user = new User();
        try {
            // 验证手机号是否已经注册
            if (userDao.findUniqueByProperty("mobile", mobile) != null) {
                // 如果是手机登录，则返回JSON字符串
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_1007);
                j.setMsg("手机号已经被使用！");
                return j;
            }
            //		// 验证短信内容
            //		if (!randomCode.equals(request.getSession().getServletContext().getAttribute(mobile))) {
            //			// 如果是手机登录，则返回JSON字符串
            //			j.setSuccess(false);
            //			j.setErrorCode("3");
            //			j.setMsg("手机验证码不正确!");
            //			return j;
            //		}

            // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
            List<Dict> dictList = DictUtils.getDictList("defalut_role");
            Dict dict = dictList.get(0);
            Role role = this.getRole(dict.getValue());


            // 密码MD5加密
            user.setPasswordRemake(password);
            user.setPassword(SystemService.entryptPassword(password));
            user.setLoginName(mobile);

            // 岗位数据有效性验证，过滤不在授权内的岗位
            /*
             * //保存机构 user.setCompany(office); user.setOffice(office);
             */
            // 生成用户二维码，使用登录名
            String realPath = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + time + "/qrcode/";
            FileUtils.createDirectory(realPath);
            String picName = time + ".png"; // encoderImgId此处二维码的图片名
            String filePath = realPath + picName; // 存放路径
            TwoDimensionCode.encoderQRCode(user.getLoginName(), filePath, "png");// 执行生成二维码
            user.setQrCode(contextPath + Global.USERFILES_BASE_URL + time + "/qrcode/" + picName);
            if (user.getQrCode() != null && !user.getQrCode().equals("")) {
                InputStream inputStream = null;
                HttpURLConnection httpURLConnection;
                try {
                    URL url = new URL(urls + user.getQrCode());
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    // 设置网络连接超时时间
                    httpURLConnection.setConnectTimeout(3000);
                    // 设置应用程序要从网络连接读取数据
                    httpURLConnection.setDoInput(true);

                    httpURLConnection.setRequestMethod("GET");
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        // 从服务器返回一个输入流
                        inputStream = httpURLConnection.getInputStream();

                    }
                    String path = new StringBuilder("qrcode/")
                            .append(user.getName()+System.currentTimeMillis()).append(".png").toString();
                    OssClient ossClient = new OssClient();
                    String url1 = ossClient.uploadFileToOss(inputStream,path);
                    user.setQrCode(url1);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    inputStream.close();
                }
            }
            user.setName(name);
            String realPathPhoto = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + time + "/img/";
            FileUtils.createDirectory(realPathPhoto);
            String picNamePhoto = time + ".png"; // encoderImgId此处二维码的图片名
            String filePathPhoto = realPathPhoto + picNamePhoto; // 存放路径
            //FontImageUtil.createImage(name.substring(0, 1), new Font("宋体", Font.BOLD, 100), new File(filePathPhoto), 200, 200);
            WordToPic.TextToPic(name.substring(name.length() - 2 > 0 ? name.length() - 2 : 0, name.length()), 200, 200, 55, filePathPhoto);
            user.setPhoto(contextPath + Global.USERFILES_BASE_URL + time + "/img/" + picNamePhoto);
            if (user.getPhoto() != null && !user.getPhoto().equals("")) {
                InputStream inputStream = null;
                HttpURLConnection httpURLConnection;
                try {
                    URL url = new URL(urls + user.getPhoto());
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    // 设置网络连接超时时间
                    httpURLConnection.setConnectTimeout(3000);
                    // 设置应用程序要从网络连接读取数据
                    httpURLConnection.setDoInput(true);

                    httpURLConnection.setRequestMethod("GET");
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        // 从服务器返回一个输入流
                        inputStream = httpURLConnection.getInputStream();

                    }
                    OSSClientUtil ossUtil = new OSSClientUtil();
                    String[] arr = user.getPhoto().split("/");
                    String photoName = time + arr[arr.length - 1];
                    ossUtil.uploadFile2OSS(inputStream, Global.getPhoto(), photoName);
                    user.setPhoto(Global.getAliyunUrl() + "/" + Global.getPhoto() + photoName);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    inputStream.close();
                }
            }
            user.setMobile(mobile);
            // 保存用户信息
            user.setDefaultPhoto("0");
            user.setComId("1");
            user.setCompany(new Office("1"));
            user.setOffice(new Office("5"));
            role.setOffice(new Office("5"));
            this.saveUserInfo(user);
            this.assignUserToRole(role, user,0);

            //屏蔽掉环信注册，加个说明
            user.setRemarks("");

            // 清除当前用户缓存
            if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
                UserUtils.clearCache();
                // UserUtils.getCacheMap().clear();
            }
            //request.getSession().getServletContext().removeAttribute(user.getMobile());// 清除验证码
            //环信注册
            //屏蔽掉环信注册
//            RegisterUsers users = new RegisterUsers();
//            io.swagger.client.model.User user1 = new io.swagger.client.model.User().username(user.getId()).password(password);
//            users.add(user1);
//            Object result = easemobIMUsers.createNewIMUserSingle(users);
//            Nickname nickname = new Nickname();
//            nickname.setNickname(user.getName());
//            easemobIMUsers.modifyIMUserNickNameWithAdminToken(user.getId(), nickname);
//            logger.info(result.toString());
//            JSONObject json = JSONObject.fromObject(result);
//            j.put("IMUser", json);

            j.setSuccess(true);
            j.setMsg("注册用户'" + user.getLoginName() + "'成功!");
            j.put("userId", user.getId());
            j.setErrorCode(ErrorCode.code_1004);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("注册用户'" + user.getLoginName() + "'失败");
            j.put("userId", user.getId());
            j.setErrorCode(ErrorCode.code_2004);
            logger.info("Exception e:"+e);
            userDao.delete(user);
        }
        return j;
    }

    @Transactional(readOnly = false)
    public void updateUserInfo(User user) {
        user.preUpdate();
        userDao.updateUserInfo(user);
        // 清除用户缓存
        UserUtils.clearCache(user);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
    }

    @Transactional(readOnly = false)
    public void updateMo(User user) {
        user.preUpdate();
        userDao.updateMo(user);
        // 清除用户缓存
        UserUtils.clearCache(user);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
    }

    @Transactional(readOnly = false)
    public void deleteUser(User user) {
        //清除环信帐号
        userDao.delete(user);
        // 清除用户缓存
        UserUtils.clearCache(user);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
    }

    @Transactional(readOnly = false)
    public void updatePasswordById(String id, String loginName,
                                   String newPassword) {
        User user = new User(id);
        user.setPassword(entryptPassword(newPassword));
        user.setPasswordRemake(newPassword);
        user.setFirstFlag("0");
        userDao.updatePasswordById(user);
        // 清除用户缓存
        user.setLoginName(loginName);
        UserUtils.clearCache(user);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
    }

    @Transactional(readOnly = false)
    public void updateUserLoginInfo(User user) {
        // 保存上次登录信息
        user.setOldLoginIp(user.getLoginIp());
        user.setOldLoginDate(user.getLoginDate());
        // 更新本次登录信息
        user.setLoginIp(UserUtils.getSession().getHost());
        user.setLoginDate(new Date());
        userDao.updateLoginInfo(user);
    }

    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     */
    public static String entryptPassword(String plainPassword) {
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt,
                HASH_INTERATIONS);
        return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
    }

    /**
     * 生成MD5加密
     */
    public static String encrypeString(String plainPassword) {
        String  password="";
        try {
            password = EncrypeUtil.encrypeString(plainPassword, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return password;
    }

    /**
     * 验证密码
     *
     * @param plainPassword
     *            明文密码
     * @param password
     *            密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) {
        byte[] salt = Encodes.decodeHex(password.substring(0, 16));
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt,
                HASH_INTERATIONS);
        return password.equals(Encodes.encodeHex(salt)
                + Encodes.encodeHex(hashPassword));
    }

    /**
     * 验证密码
     *
     *            密文密码
     * @return 验证成功返回true
     */
    public List<User> getUserListByEnname(String userId, String companyId,String enname) {
        //该公司下所有的岗位
        List<Role> roleList = getRoleList("",companyId);
        Role role = new Role();
        if (roleList!=null && roleList.size()!=0){
            for (Role r :roleList){
                //要的是管理员
                if (r.getEnname().endsWith(enname)){
                    role = r;
                    break;
                }
            }
        }
        //该公司下拥有管理员岗位的所有员工
        role.setCompany(new Office(companyId));
        List<User> userList = userDao.findUserByRole(role);
        return userList;
    }

    /**
     * 获得活动会话
     *
     * @return
     */
    public Collection<Session> getActiveSessions() {
        return sessionDao.getActiveSessions(false);
    }

    // -- Role Service --//

    public Role getRole(String id) {
        return roleDao.get(id);
    }

    public Role getRoleMenu(String id) {
        return roleDao.getMenuList(id);
    }

    public Role getRoleByName(String name,String companyId) {
        Role r = new Role();
        r.setName(name);
        r.setCompany(new Office(companyId));
        return roleDao.getByName(r);
    }

    public Role getRoleByEnname(String companyId,Office office,String enname) {
        Role r = new Role();
        r.setEnname(enname);
        r.setCompany(new Office(companyId));
        if (office==null || StringUtils.isBlank(office.getId())){
            r.setOffice(officeDao.getByOfficeInfo(new Office(companyId)));
        }else {
            r.setOffice(office);
        }
        Role role = roleDao.getByEnname(r);
        return role;

    }

    public SysRoleActivity getRoleActivityByEnname(String enname) {
        return roleActivityDao.getByEnname(enname);
    }

    public List<Role> findRole(Role role) {
        return roleDao.findList(role);
    }
    public List<Role> findListRole(Role role) {
        return roleDao.findListRole(role);
    }
    public Page<Role> findPageRole(Page<Role> page,Role role) {
        role.setPage(page);
        List<Role> roles = findListRole(role);
        page.setList(roles);
        return page;
    }
    public Page<Role> findPageRoleByUser(Page<Role> page,Role role) {
        role.setPage(page);
        List<Role> roles = roleDao.findRoleList(role);
        page.setList(roles);
        return page;
    }
    public List<Role> findListRoleByUser(Role role) {
        List<Role> roles = roleDao.findRoleList(role);
        return roles;
    }

    public List<Role> findAllRole() {
        return UserUtils.getRoleList();
    }

    public List<Role> findAllRoleByCompany() {
        return UserUtils.getRoleListByCompany("");
    }

    @Transactional(readOnly = false)
    public String saveRole(Role role,Boolean b,int type) {
        Office office = officeDao.get(role.getOffice());
        if (StringUtils.isNotBlank(office.getBranchOffice())){
            role.setBranchCompany(new Office(office.getBranchOffice()));
        }
        if (role.getCompany().getId().equals("1")){
            String parentIds = office.getParentIds();
            for (String parentId:parentIds.split(",")){
                if (!parentId.equals("0")) {
                    Office o = officeDao.get(parentId);
                    if (o.getType().equals("1")) {
                        role.setCompany(o);
                        break;
                    }
                }
            }
        }
        String str = "";
        if (StringUtils.isBlank(role.getEnname())){
            String enname = StringUtils.getPinYinHeadChar(role.getName(), 1);
            role.setEnname(enname);
        }
        if (StringUtils.isBlank(role.getId())) {
            role.preInsert();
            roleDao.insert(role);
        } else {
            role.preUpdate();
            //修改时间
            roleDao.update(role);
        }
        if (b){
            // 更新岗位与菜单关联
            Role role1 = new Role(role.getId());
            roleDao.deleteRoleMenu(role1);
            //roleDao.deleteRoleMenu(role);//删除岗位id 关联表
            logger.info("角色菜单id：------------------------------");
            if (role.getMenuList().size() > 0) {
                for (Menu menu:role.getMenuList()){
                    System.out.print(menu.getId()+",");
                }
                //插入岗位与权限
                try{
                    role1.setMenuList(role.getMenuList());
                    roleDao.insertRoleMenu(role1);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            logger.info("------------------------------");
        }

        // 删除岗位与部门关联
                /*roleDao.deleteRoleOffice(role);
                if (role.getOfficeList().size() > 0) {
                    try{
                        roleDao.insertRoleOffice(role);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }*/
        // 清除用户岗位缓存
        UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
        List<User> users = findUserByRoleId(role);
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            if (users!=null && users.size()!=0){
                for (User user :users){
                    UserUtils.clearCache(user);
                    jedis.del("menu1_"+user.getComId()+"_" + user.getId());
                    jedis.del("menu2_"+user.getComId()+"_" + user.getId());
                    UserUtils.clearCache(user);
                }

                removeSession(users);
            }
            //String sql = jedis.hget("menu2_user_" + user.getId(), menuId);
        }catch (Exception e){
            System.out.println("------------------dataScopeFilterOR Exception e:"+e);
        }finally {
            JedisUtils.returnResource(jedis);
        }

        if (type == 0){
            relationRoleActivitys(role);
        }
        str = "成功!";
        return str;

    }

    @Transactional(readOnly = false)
    public List<User> findUserByRoleId(Role role){
        List<User> users =  userDao.findUserByRoleId(role.getId(),role.getCompany().getId());
        return users;
    }
    @Transactional(readOnly = false)
    public Boolean relationRoleActivity(Role role) {
        String[] ids = role.getRoleActivityIds().split(",");
        List<SysRoleActivity> roleActivities = new ArrayList<>();
        for (String roleActivityId:ids){
            roleActivities.add(new SysRoleActivity(roleActivityId));
        }
        role.setRoleActivityList(roleActivities);
        //roleDao.deleteRoleActivity(role);
        int count = roleDao.insertRoleActivity(role);
        if (count!=0){
            return true;
        }else {
            return false;
        }
    }

    @Transactional(readOnly = false)
    public Boolean relationRoleActivitys(Role role) {
        List<SysRoleActivity> sysRoleActivities = role.getRoleActivityList();
        List<SysRoleActivity> roleActivities = new ArrayList<>();
        for (SysRoleActivity sysRoleActivity:sysRoleActivities){
            if (sysRoleActivity.getDelFlag().equals("0")){
                roleActivities.add(new SysRoleActivity(sysRoleActivity.getId()));
            }
        }
        role.setRoleActivityList(roleActivities);
        roleDao.deleteRoleActivity(role);
        if (role.getRoleActivityList()!=null && role.getRoleActivityList().size()!=0) {
            int count = roleDao.insertRoleActivity(role);
            if (count!=0){
                return true;
            }else {
                return false;
            }
        }else {
            return true;
        }
    }
    @Transactional(readOnly = false)
    public Boolean deleteRoleActivity(Role role) {
        String[] ids = role.getRoleActivityIds().split(",");
        List<SysRoleActivity> roleActivities = new ArrayList<>();
        for (String roleActivityId:ids){
            roleActivities.add(new SysRoleActivity(roleActivityId));
        }
        role.setRoleActivityList(roleActivities);
        roleDao.deleteRoleActivity(role);
        return true;
    }
    @Transactional(readOnly = false)
    public Boolean deleteRoleActivityOne(String roleId,String roleActivityId) {
        roleDao.deleteRoleActivityOne(roleId,roleActivityId);
        return true;
    }
    @Transactional(readOnly = false)
    public Boolean deleteRole(Role role) {
        Boolean b = false;
        try {
            int userCount = roleDao.findUserRoleCount(role);
            if (userCount==0){
                roleDao.delete(role);
                roleDao.deleteRoleMenu(role);
                roleDao.deleteRoleActivity(role);
                // 清除用户岗位缓存
                UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
                // // 清除权限缓存
                // systemRealm.clearAllCachedAuthorizationInfo();
                b = true;
            }

        }catch (Exception e){
            logger.info("deleteRole:Exception e："+e);
        }
        return b;
    }

    @Transactional(readOnly = false)
    public Boolean outUserInRole(Role role, User user) {
        try {
            List<Role> roles = user.getRoleList();
            for (Role e : roles) {
                if (e.getId().equals(role.getId())) {
                    roles.remove(e);
                    if (StringUtils.isNotBlank(user.getId())) {
                        // 更新用户与岗位关联
                        userDao.deleteUserRole(user);
                        if (user.getRoleList() != null && user.getRoleList().size() > 0) {
                            userDao.insertUserRole(user);
                        } else {
                            List<Role> roleList = new ArrayList<>();
                            Role role1 = new Role();
                            role1.setId("1");
                            role1.setOffice(new Office("5"));
                            roleList.add(role1);
                            user.setRoleList(roleList);
                            userDao.insertUserRole(user);
                        }
                        delMenuCache(user);
                        UserUtils.clearCache(user);
                        removeSession(user);
                        // // 清除权限缓存
                        // systemRealm.clearAllCachedAuthorizationInfo();
                    }
                    return true;
                }
            }
        }catch (Exception e){
            logger.info("outUserInRole:Exception e："+e);
        }

        return false;
    }

    public void delMenuCache(User user) {
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getResource();
            jedis.del("menu1_"+user.getComId()+"_" + user.getId());
            jedis.del("menu2_"+user.getComId()+"_" + user.getId());
        }catch (Exception e){
            logger.error("清除用户权限缓存异常！userId:{}",user.getId(),e);
        }finally {
            JedisUtils.returnResource(jedis);
        }
    }

    @Transactional(readOnly = false)
    public User addUserToRole(User user) {
        try {
            if (user == null) {
                return null;
            }
            User user1 = new User();
            Role role = new Role();
            role.setOffice(new Office("5"));
            role.setId("1");
            user1.setId(user.getId());
            user1.getRoleList().add(role);
            user1.setRole(role);
            user1.setId(user.getId());
            userDao.insertUserRole(user1);
            user.setRemove("");
            // 清除用户缓存
            delMenuCache(user);
            UserUtils.clearCache(user);
            removeSession(user);
            return user;
        }catch (Exception e){
            logger.info("assignUserToRole:Exception e："+e);
        }
        return null;
    }

    @Transactional(readOnly = false)
    public User assignUserToRole(Role role, User user,int type) {
        try {
            if (user == null) {
                return null;
            }
            if (role.getDataScope().equals("1")){
                return null;
            }
            List<Role> roleList = new ArrayList<>();
            roleList.addAll(user.getRoleList());
            int count = 0;
            for (Role role1:roleList){
                if (role1.getId().equals(role.getId())) {
                    return new User("1");
                }else if (role1.getId().equals("1")){
                    count++;
                    User user1 = new User();
                    Role role2 = new Role();
                    role2.setOffice(new Office("5"));
                    role2.setId("1");
                    user1.setRole(role2);
                    user1.setId(user.getId());
                    user.getRoleList().remove(role1);
                    userDao.deleteUserRole(user1);
                }
            }
            user.getRoleList().add(role);
            User user1 = new User();
            user1.setId(user.getId());
            user1.getRoleList().add(role);
            Role role2 = new Role();
            role2.setOffice(role.getOffice());
            role2.setId(role.getId());
            user1.setRole(role2);
            userDao.insertUserRole(user1);
            user.setRemove("");
            if (count != 0){
                user.setRemove("remove");
            }
            delMenuCache(user);
            if (type == 0) {
                // 清除用户缓存
                UserUtils.clearCache(user);
                removeSession(user);
            }
            return user;
        }catch (Exception e){
            logger.error("assignUserToRole:Exception e：",e);
        }
        return null;
    }
    @Transactional(readOnly = false)
    public int assignUserToRoleList(List<Role> roleLists, User user) {
        int count = 0;
        try {
            if (user == null) {
                return 0;
            }
            List<Role> roleList = user.getRoleList();
            for (Role role1 : roleList) {
                for (Role role : roleLists) {
                    if (role1.getId().equals(role.getId())) {
                        return 0;
                    } else if (role1.getId().equals("1")) {
                        User user1 = new User();
                        Role role2 = new Role();
                        user1.setId(user.getId());
                        role2.setOffice(new Office("5"));
                        role2.setId("1");
                        user1.setRole(role2);
                        user.getRoleList().remove(role1);
                        userDao.deleteUserRole(user1);
                    }
                }
            }
            for (Role role : roleLists) {
                try {
                    user.getRoleList().add(role);
                    User user1 = new User();
                    Role role2 = new Role();
                    user1.setId(user.getId());
                    user1.getRoleList().add(role);
                    role2.setOffice(role.getOffice());
                    role2.setId(role.getId());
                    user1.setRole(role2);
                    userDao.insertUserRole(user);
                    count ++;
                }catch (Exception e){
                    logger.error("数据重复");
                }
            }
            user.setRemove("");
            if (count != 0) {
                user.setRemove("remove");
                // 清除用户缓存
                UserUtils.clearCache(user);
                removeSession(user);
            }
         }catch (Exception e){
            logger.info("assignUserToRoleList:Exception e："+e);
            count = -1;
        }
        return count;
    }

    @Transactional(readOnly = false)
    public User updateUserToRole(Role role, User user) {
        try {
            if (user == null) {
                return null;
            }
            List<Role> roleList = user.getRoleList();
            for (Role role1:roleList){
                if (role1.getOffice().equals(role.getOffice()) && role1.getId().equals(role.getId())) {
                    User user1 = new User();
                    user1.setId(user.getId());
                    Role role2 = new Role();
                    role2.setOffice(role.getOffice());
                    role2.setId(role.getId());
                    user1.setRole(role2);
                    user.getRoleList().remove(user1);
                    userDao.deleteUserRole(user1);
                }else {
                    return null;
                }
            }
            // 清除用户缓存
            UserUtils.clearCache(user);
            removeSession(user);
            return user;
        }catch (Exception e){
            logger.info("updateUserToRole:Exception e："+e);
        }
        return null;

    }

    public Office getSelectCompany() {
        Object companyId = UserUtils.getCache("selectCompany");
        if (companyId != null) {
            Office company = officeDao.get(companyId.toString());
            return company;
        }

        return null;
    }

    @Transactional(readOnly = true)
    public List<Role> getRoleList(String userId,String companyId) {
        Role roles = new Role();
        if (StringUtils.isNotBlank(userId)){
            User user = UserUtils.get(userId);
            roles.setUser(user);
        }
        List<Role> roleList = new ArrayList<>();
        if (StringUtils.isNotBlank(companyId)){
            if (companyId.equals("1")){
                roles.setCompany(new Office("1"));
            }else {
                roles.setCompany(new Office(companyId));
                roleList = roleDao.findList(roles);
            }
        }else {
            roleList = roleDao.findList(roles);
        }
        return roleList;
    }


    @Transactional(readOnly = false)
    public List<Map<String,Object>> getCurrentCompany(String userId) {
        User user =UserUtils.get(userId);

        List<Office> companyList = UserUtils.getAllCompany(user);
        HashSet<Office> hs = new HashSet<Office>(companyList);
        List<Map<String,Object>> mapList = Lists.newArrayList();
        if (hs!=null &&hs.size()!=0) {
            for (Office off : hs) {
                if (!off.getId().equals("1")) {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("companyName", off.getName());
                    map.put("companyLogo", off.getLogo() == null ? "" : off.getLogo());
                    map.put("companyQrcode", off.getCompanyQrcode() == null ? "" : off.getCompanyQrcode());
                    map.put("companyId", off.getId());
                    map.put("branchOfficeId", off.getBranchOffice());
                    if (StringUtils.isNotBlank(off.getBranchOffice())){
                        Office branchOffice = officeDao.get(off.getBranchOffice());
                        map.put("branchOfficeName", branchOffice.getName());
                    }else {
                        map.put("branchOfficeName", off.getName());
                    }
                    map.put("master", off.getMaster() == null || UserUtils.get(off.getMaster()) == null ? "" : UserUtils.get(off.getMaster()).getName());
                    map.put("masterId", off.getMaster() == null ? "" : off.getMaster());
                    Useroffice useroffice = new Useroffice();
                    useroffice.setCompanyId(off.getId());
                    useroffice.setStatus("3");
                    List<Useroffice> userofficeList = userofficeService.findList(useroffice);
                    map.put("count", userofficeList.size());
                    for (Useroffice useroffice1:userofficeList){
                        if (useroffice1.getUserId().equals(user.getId())){
                            map.put("officeId", useroffice1.getOfficeId());
                            if (StringUtils.isNotBlank(useroffice1.getOfficeId())){
                                map.put("officeName", officeService.get(useroffice1.getOfficeId()).getName());
                            }else {
                                map.put("officeName","");
                            }
                        }
                    }
                    Role role2 = new Role();
                    role2.setCompany(off);
                    role2.setUser(UserUtils.get(userId));
                    List<Role> roleList2 = roleDao.findList(role2);
                    for (Role role : roleList2) {
                        /*map.put("officeId", role.getOffice().getId());
                        map.put("officeName", role.getOffice().getName());*/
                        if(user!=null && user.getComId()!=null && user.getComId().equals(off.getId())){
                            map.put("isCurrent", 1);
                            if(UserUtils.getUser().isAdmin() || (StringUtils.isNotBlank(role.getEnname()) && (role.getEnname().endsWith("gly")||role.getEnname().equals("system")))){
                                map.put("isManager","1");
                                if (role.getCompany() == null || StringUtils.isBlank(role.getCompany().getId())){
                                    role.setCompany(UserUtils.getSelectCompany());
                                }
                                List<User> userList2 = userDao.findUserByRole(role);
                                for (int k = 0; k < userList2.size(); k++) {
                                    if (userList2.get(k) != null || userList2.get(k).equals("null")) {
                                        map.put("glyName", userList2.get(k).getName());
                                    }
                                }
                                break;
                            }else{
                                map.put("isManager","0");
                                map.put("glyName", "");
                            }
                        }else {
                            map.put("isCurrent", 0);
                        }
                    }
                    mapList.add(map);
                }
            }
        }

        return mapList;
    }
    @Transactional(readOnly = false)
    public List<Map<String,Object>> saveCurrentCompany(String userId,String companyId) {
        UserUtils.saveSelectCompany();
        return getCurrentCompany(userId);
    }

    @Transactional(readOnly = false)
    public List<Map<String,Object>> saveCurrentCompanyById(String userId,String companyId,String officeId) {
        User user=UserUtils.get(userId);
        if (companyId != null) {
            user.setComId(companyId);
            user.setCompany(new Office(companyId));
        }
        if (officeId != null){
            user.setOffice(new Office(officeId));
        }
        // 清除原用户机构用户缓存
        User oldUser = userDao.get(userId);
        if (oldUser.getOffice() != null
                && oldUser.getOffice().getId() != null) {
            CacheUtils.remove(UserUtils.USER_CACHE,
                    UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_
                            + oldUser.getOffice().getId());
            CacheUtils.remove(UserUtils.USER_CACHE,
                    UserUtils.CACHE_COMPANY
                            + oldUser.getComId());
        }
        user.preUpdate();
        userDao.updateUserInfo(user);
        if (UserUtils.getUser().getId().equals(userId)){
            UserUtils.clearCache();
            UserUtils.removeCache("selectCompany");
            UserUtils.removeCache("selectOffice");
            UserUtils.removeCache("selectRole");
            UserUtils.putCache("selectCompany", companyId);
            UserUtils.putCache("selectOffice", officeId);
            Role role = new Role();
            role.setCompany(getSelectCompany());
            role.setUser(user);
            List<Role> roleList = roleDao.findList(role);
            if(roleList!=null && roleList.size()!=0){
                UserUtils.putCache("selectRole", roleList);
            }
        }
        return getCurrentCompany(userId);
    }

    // -- Menu Service --//

    public Menu getMenu(String id) {
        return menuDao.get(id);
    }

    public List<Menu> findAllMenu() {
        return UserUtils.getMenuList();
    }
    public List<Menu> findAllMenu(Role role) {
        return UserUtils.getMenuList(role);
    }

    @Transactional(readOnly = false)
    public void saveMenu(Menu menu) {

        // 获取父节点实体
        menu.setParent(this.getMenu(menu.getParent().getId()));

        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = menu.getParentIds();

        // 设置新的父节点串
        menu.setParentIds(menu.getParent().getParentIds()
                + menu.getParent().getId() + ",");

        // 保存或更新实体
        if (StringUtils.isBlank(menu.getId())) {
            menu.preInsert();
            menuDao.insert(menu);
        } else {
            menu.preUpdate();
            menuDao.update(menu);
        }

        // 更新子节点 parentIds
        Menu m = new Menu();
        m.setParentIds("%," + menu.getId() + ",%");
        List<Menu> list = menuDao.findByParentIdsLike(m);
        for (Menu e : list) {
            e.setParentIds(e.getParentIds().replace(oldParentIds,
                    menu.getParentIds()));
            menuDao.updateParentIds(e);
        }
        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
    }

    @Transactional(readOnly = false)
    public void updateMenuSort(Menu menu) {
        menuDao.updateSort(menu);
        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
    }

    @Transactional(readOnly = false)
    public void deleteMenu(Menu menu) {
        menuDao.delete(menu);
        // 清除用户菜单缓存
        UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
        // // 清除权限缓存
        // systemRealm.clearAllCachedAuthorizationInfo();
        // 清除日志相关缓存
        CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
    }

    /**
     * 获取Key加载信息
     */
    public static boolean printKeyLoadMessage() {
        StringBuilder sb = new StringBuilder();
        sb.append("\r\n======================================================================\r\n");
        sb.append("\r\n    欢迎使用 " + Global.getConfig("productName")
                + "  - Powered By http://www.jeeplus.org\r\n");
        sb.append("\r\n======================================================================\r\n");
        System.out.println(sb.toString());
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub

    }
    @Autowired
    private JedisSessionDAO jedisSessionDAO;
    public JedisSessionDAO getJedisSessionDao() {
        return jedisSessionDAO;
    }
    public Collection<Session> getSessionList() {
        return getJedisSessionDao().getActiveSessions(false);
    }

    public String removeSession(List<User> users) {
        String str = "";
        if (users != null && users.size() != 0) {
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                Long delCount = 0L;
                /*Long delCount = 0L;
                String sessionPrefix = Global.getConfig("redis.keyPrefix") + "_session_";
                Map<String, String> map = jedis.hgetAll(sessionPrefix);
                for (Map.Entry<String, String> e : map.entrySet()) {
                    if (StringUtils.isNotBlank(e.getKey()) && StringUtils.isNotBlank(e.getValue())) {
                        String[] ss = StringUtils.split(e.getValue(), "|");
                        if (ss != null && ss.length == 3) {

                            String principalId = ss[0];
                            for (User user:users){
                                if (StringUtils.isNotBlank(principalId) && principalId.equals(user.getId())) {
                                    String jsessionId = sessionPrefix + e.getKey();
                                    if (StringUtils.isNotBlank(e.getKey())) {
                                        delCount += jedis.del(jsessionId);
                                        jedis.hdel(sessionPrefix, e.getKey());
                                    }
                                }
                            }
                        }
                    }
                }*/
            Collection<Session> sessions = getSessionList();
            logger.info("sessionKeyPrefix:"+sessionKeyPrefix+","+ com.alibaba.fastjson.JSON.toJSONString(jedis.hgetAll(sessionKeyPrefix)));
            for (Session session :sessions){
                String pid = jedis.hget(sessionKeyPrefix,session.getId().toString());
                for (User user :users) {
                    if (pid != null && pid.contains(user.getId())) {
                        getJedisSessionDao().delete(session);
                        clearCache(user);
                        delCount++;
                    }
                }
            }
            logger.info("sessions:"+sessions);
                if (delCount < 1) {
                    System.err.println("删除用户的session失败");
                    str = "删除用户的session失败";
                } else {
                    System.err.println("删除用户的session成功");
                    str = "删除用户的session成功";
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return str;
        } else {
            return "用户信息为空！";
        }


    }

    public String removeSession(User user){
        String str = "";
        if(StringUtils.isNotBlank(user.getId())){

            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                Long delCount = 0L;
                Collection<Session> sessions = getSessionList();
                logger.info("sessionKeyPrefix:"+sessionKeyPrefix+","+ com.alibaba.fastjson.JSON.toJSONString(jedis.hgetAll(sessionKeyPrefix)));
                for (Session session :sessions){
                    String pid = jedis.hget(sessionKeyPrefix,session.getId().toString());
                    if (pid!=null && pid.contains(user.getId())){
                        clearCache(user);
                        getJedisSessionDao().delete(session);
                        delCount++;
                    }
                }
                /*String sessionPrefix = Global.getConfig("redis.keyPrefix")+"_session_";
                Map<String, String> map = jedis.hgetAll(sessionPrefix);
                for (Map.Entry<String, String> e : map.entrySet()){
                    if (StringUtils.isNotBlank(e.getKey()) && StringUtils.isNotBlank(e.getValue())){
                        String[] ss = StringUtils.split(e.getValue(), "|");
                        if (ss != null && ss.length == 3){

                            String principalId = ss[0];
                            if(StringUtils.isNotBlank(principalId) && principalId.equals(user.getId())){
                                String jsessionId = sessionPrefix+e.getKey();
                                if (StringUtils.isNotBlank(e.getKey())){
                                    jedis.hdel(sessionPrefix, e.getKey());
                                    delCount += jedis.del(jsessionId);
                                }
                            }
                        }
                    }
                }*/
                if (delCount<1){
                    System.err.println("删除"+user.getName()+"的session失败");
                    str = "删除"+user.getName()+"的session失败";
                }else{
                    System.err.println("删除"+user.getName()+"的session成功");
                    str = "删除"+user.getName()+"的session成功";
                }
            }catch (Exception e){
                e.printStackTrace();
            } finally {
                JedisUtils.returnResource(jedis);
            }
            return str;
        }else{
            return "用户信息为空！";
        }

    }

    public void clearCache(User user) {
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        Collection<Realm> realms = securityManager.getRealms();
        for (Realm realm : realms) {
            SystemAuthorizingRealm realm1 = (SystemAuthorizingRealm)realm;
            realm1.clearCachedAuthorizationInfo(new SystemAuthorizingRealm.Principal(user,false));
        }
    }

    public User findUserByNo(String no) {
        Office company = UserUtils.getSelectCompany();
        return userDao.findUserByNo(no,company.getId());
    }

    public int countByOffice(Office office) {
        User user = new User();
        user.setOffice(office);
        return userDao.countByOffice(user);
    }
}
