package cn.estsh.i3plus.core.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ICoreTreeService;
import cn.estsh.i3plus.core.api.iservice.busi.IPersonnelService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysUserInfoService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysUserService;
import cn.estsh.i3plus.core.apiservice.dao.IUserPermissionDao;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.EncryptTool;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.shirotoken.UserToken;
import cn.estsh.i3plus.pojo.base.tool.HqlPack;
import cn.estsh.i3plus.pojo.platform.bean.*;
import cn.estsh.i3plus.pojo.platform.repository.*;
import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description : 平台用户业务
 * @Reference :
 * @Author : wei.peng
 * @Date : 2018-10-25 17:45
 * @Modify :
 **/
@Service
public class SysUserService implements ISysUserService {

    public static final Logger LOGGER = LoggerFactory.getLogger(SysUserService.class);

    @Autowired
    private SysUserRepository sysUserRDao;

    @Autowired
    private SysUserInfoRepository sysUserInfoRDao;

    @Autowired
    private IUserPermissionDao userPermissionDao;

    @Autowired
    private SysOrganizeRepository organizeRDao;

    @Autowired
    private SysRoleRepository sysRoleRDao;

    @Autowired
    private SysRefUserRoleRepository refUserRoleRDao;

    @Autowired
    private SysRefUserDepartmentRepository refUserDepartmentRDao;

    @Autowired
    private SysRefUserPositionRepository refUserPositionRDao;

    @Autowired
    private SysFileRepository sysFileRDao;

    @Autowired
    private SysDepartmentRepository departmentRDao;

    @Autowired
    private SysPositionRepository sysPositionRDao;

    @Autowired
    private ISysUserInfoService sysUserInfoService;

    @Autowired
    private SysLogUserLoginRepository logUserLoginRDao;

    @Autowired
    private SysMenuRepository sysMenuRDao;

    @Autowired
    private ICoreTreeService coreTreeService;

    @Autowired
    private IPersonnelService personnelService;

    @Override
    @ApiOperation(value = "用户登录", notes = "用户登录功能实现")
    public SessionUser queryUserLogin(String loginName, String password, String languageCode) throws AuthenticationException {
        LOGGER.debug("平台用户 SYS_USER loginName:{} \t password:{} \t languageCode:{}", loginName, password, languageCode);

        UserToken token = new UserToken(loginName,password,languageCode);
        SessionUser sessionUser = AuthUtil.login(token);
        SysUser user = this.getSysUserByLoginName(loginName);

        if(user == null){
            throw new CredentialsException("用户不存在");
        }

        packSessionUser(sessionUser, user, user.getUserType(), languageCode);
        AuthUtil.setSessionUser(sessionUser);
        refreshUserLoginInformation(user.getId());
        return sessionUser;
    }

    @Override
    @ApiOperation(value = "修改账号", notes = "修改账号状态")
    public void updateSysUserStatus(Long id, int status, SessionUser user) {
        LOGGER.debug("平台用户 SYS_USER id:{} status:{} modifyUser:{}", id, status, user.getUserName());
        SysUser sysUser = sysUserRDao.getById(id);
        sysUser.setUserStatus(status);
        sysUser.setModifyUser(user.getUserName());
        sysUserRDao.update(sysUser);
    }

    @Override
    @ApiOperation(value = "修改账号", notes = "批量修改账号状态")
    public void updateBatchSysUserStatus(Long[] ids, int status, SessionUser user) {
        LOGGER.debug("平台用户 SYS_USER DELETE By ids :{} status:{}, SessionUser :{}", ids,status,user);

        String where = CoreHqlPack.packHqlIds("id", ids);
        List<SysUser> list = sysUserRDao.findByHqlWhere(where);
        if(null != list && list.size() > 0){
            for (SysUser sysUser : list) {
                sysUser.setUserStatus(status);
                sysUser.setIsValid(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                ConvertBean.modelUpdate(sysUser,user);
            }
            sysUserRDao.saveAll(list);
        }
    }

    @Override
    @ApiOperation(value = "修改账号", notes = "修改账号信息")
    public void updateSysUser(SysUser sysUser) throws Exception{
        LOGGER.debug("平台用户 SYS_USER SysUser :{}", sysUser);
        sysUserRDao.save(sysUser);
    }

    @Override
    @ApiOperation(value = "修改账号", notes = "修改账号登录密码")
    public void updateSysUserPassword(Long userId, String password, String newPwd) throws Exception {
        LOGGER.debug("平台用户 SYS_USER Override:{} password:{} newPwd:{}", userId,password,newPwd);
        SysUser user = sysUserRDao.getById(userId);
        if(user != null){
            String pwdMd5 = EncryptTool.hexMD5(password);
            if(pwdMd5.equals(user.getUserLoginPassword())){
                user.setUserLoginPassword(EncryptTool.hexMD5(newPwd));
                sysUserRDao.save(user);
            }else {
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("旧密码错误")
                        .setErrorSolution("请重新输入")
                        .build();
            }
        }else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("用户不存在")
                    .setErrorSolution("请重新操作")
                    .build();
        }
    }

    @Override
    @ApiOperation(value = "刷新账号", notes = "刷新账号登录信息")
    public void refreshUserLoginInformation(Long userId) {
        SysUser user = sysUserRDao.getById(userId);
        user.setUserLoginLastDateTime(TimeTool.getNowTime(true));
        user.setUserLoginNum(user.getUserLoginNum() + 1);
        sysUserRDao.save(user);

        SysUserInfo userInfo = sysUserInfoRDao.getById(user.getUserInfoId());
        userInfo.setUserLoginLastDateTime(TimeTool.getNowTime(true));
        userInfo.setUserLoginNum(userInfo.getUserLoginNum() + 1);
        sysUserInfoRDao.save(userInfo);
    }

    @Override
    @ApiOperation(value = "新增账号", notes = "新增账号信息")
    public SysUser insertSysUser(SysUser sysUser)throws Exception {
        LOGGER.debug("平台用户 SYS_USER SysUser:{}", sysUser);

        SysUser loginUser = getSysUserByLoginName(sysUser.getUserLoginName());
        if (null == loginUser) {
            // 密码加密 输入的密码不等于密码一致时修改密码
            String md5 = EncryptTool.hexMD5(sysUser.getUserLoginPassword());
            sysUser.setUserLoginPassword(md5);
            return sysUserRDao.insert(sysUser);
        } else {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                    .setErrorCode(ImppExceptionEnum.IO_EXCEPTION.getCode())
                    .setErrorDetail("用户名已存在")
                    .setErrorSolution("请重新输入用户名")
                    .build();
        }
    }

    @Override
    @ApiOperation(value = "新增登录日志",notes = "新增登录日志信息")
    public SysLogUserLogin insertSysLogUserLogin(SysLogUserLogin sysLogUserLogin) {
        LOGGER.debug("平台用户登录记录 SysLogUserLogin sysLogUserLogin:{}", sysLogUserLogin);
        return logUserLoginRDao.insert(sysLogUserLogin);
    }

    @Override
    @ApiOperation(value = "新增账号", notes = "新增账号信息")
    public void refreshSysRefUserRole(SysUser sysUser, Long[] roleIds, String userName) {
        LOGGER.debug("平台用户 SYS_USER SysUser:{}", sysUser);
        LOGGER.debug("平台用户 SYS_USER String[] :{}", roleIds);

        // 根据IDS 查询所有的角色信息
        String where = CoreHqlPack.packHqlIds("id", roleIds);
        List<SysRole> list = sysRoleRDao.findByHqlWhere(where);

        // 删除角色关系信息
        refUserRoleRDao.deleteByProperty("userId", sysUser.getId()); // 删除用户角色关系

        if(null != list && list.size() > 0){
            // 新增用户角色关系
            List<SysRefUserRole> refUserRoles = new ArrayList<>();
            List<String> roleNameList = new ArrayList<>();
            SysRefUserRole refUserRole = null;
            for (SysRole role : list) {
                roleNameList.add(role.getName());
                // 用户角色关系创建
                refUserRole = new SysRefUserRole();
                refUserRole.setRoleId(role.getId());
                refUserRole.setRoleNameRdd(role.getName());
                refUserRole.setUserId(sysUser.getId());
                refUserRole.setUserNameRdd(sysUser.getUserName());
                refUserRole.setCreateUser(userName);
                refUserRole.setCreateDatetime(TimeTool.getNowTime(true));
                refUserRole.setModifyUser(userName);
                refUserRole.setModifyDatetime(TimeTool.getNowTime(true));

                refUserRoles.add(refUserRole);
            }
            refUserRoleRDao.saveAll(refUserRoles);

            // 角色名称冗余
//            sysUser.setRoleNameRdd(String.join(",", roleNameList));

            sysUserRDao.save(sysUser);
        }
    }

    @Override
    @ApiOperation(value = "删除账号", notes = "删除账号信息，逻辑删除，账号关系业务物理删除")
    public void deleteSysUserById(Long id) {
        LOGGER.debug("平台用户 SYS_USER DELETE By id :{}", id);
        SysUser user = sysUserRDao.getById(id);
        user.setIsValid(CommonEnumUtil.IS_VAILD.INVAILD.getValue());
        sysUserRDao.save(user);

        // 删除用户关系(物理删除)
        refUserRoleRDao.deleteByProperty("userId", id); // 删除用户角色关系
        refUserDepartmentRDao.deleteByProperty("userId", id); //删除用户部门关系
        refUserPositionRDao.deleteByProperty("userId", id); //删除用户部门关系
        sysUserInfoService.refreshUserInfoUserNum(user.getUserInfoId());
    }

    @Override
    @ApiOperation(value = "删除账号", notes = "批量删除账号信息，逻辑删除，账号关系业务物理删除")
    public void deleteBatchSysUserById(Long[] ids,SessionUser user) {
        LOGGER.debug("平台用户 SYS_USER DELETE By ids :{}", ids);

        // 标记用户已删除
        String where = CoreHqlPack.packHqlIds("id", ids);
        List<SysUser> list = sysUserRDao.findByHqlWhere(where);
        if(null != list && list.size() > 0){
            for (SysUser sysUser : list) {
                sysUser.setIsValid(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
            }

            sysUserRDao.saveAll(list);
            refUserRoleRDao.deleteByPropertyIn("userId",ids);
        }
    }

    @Override
    @ApiOperation(value = "账号查询", notes = "查询所有账号信息")
    public List<SysUser> list() {
        LOGGER.debug("平台用户 SYS_USER find All");
        return sysUserRDao.findByProperty("isValid", CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
    }

    @Override
    @ApiOperation(value = "查询用户ID 集合",notes = "根据角色Id 查询用户ID集合")
    public List<Long> findSysUserIdListByRoleId(Long roleId) {
        List<Long> result = new ArrayList<>();
        if(roleId != null){
            List<SysRefUserRole> list = refUserRoleRDao.findByProperty(
                    new String[]{"roleId","isValid"},
                    new Object[]{roleId,CommonEnumUtil.IS_VAILD.VAILD.getValue()});
            if(list != null && list.size() > 0){
                for (SysRefUserRole ref : list) {
                    result.add(ref.getUserId());
                }
            }
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询用户ID 集合",notes = "根据部门Id 查询用户ID集合")
    public List<Long> findSysUserIdListByDepartmentId(List<Long> idList) {
        List<Long> result = new ArrayList<>();
        if(idList != null){
            StringBuffer hqlWhere = new StringBuffer();
            HqlPack.getInPack(StringUtils.join(idList, ","), "departmentId", hqlWhere);
            List<SysRefUserDepartment> list = refUserDepartmentRDao.findByHqlWhere(hqlWhere.toString());
            if(list != null && list.size() > 0){
                for (SysRefUserDepartment ref : list) {
                    result.add(ref.getUserId());
                }
            }
        }
        return result;
    }

    @Override
    @ApiOperation(value = "账号分页查询", notes = "组合查询")
    public ListPager<SysUser> querySysUserByPager(SysUser user, Pager pager) {
        LOGGER.debug("系统用户 SysUser find user :{} page :{}", user, pager);

        // 角色查询
        if(user.getRoleId() != null){
            List<Long> ids = findSysUserIdListByRoleId(Long.parseLong(user.getRoleId()));
            user.setRoleIdList(StringTool.getListString(ids));
        }

        List<Long> departmentIdList = new ArrayList<>();
        if(user.getOrganizeId() != null){

            // 查出所有组织 ID 集合
            SysOrganize parent = coreTreeService.getSysOrganizeTreeById(user.getOrganizeId());
            List<Long> childIds = coreTreeService.findSysOrganizeChildIds(parent);

            // 查询所有部门 ID 集合
            if(childIds != null && childIds.size() > 0){
                for (Long organizeId : childIds) {
                    List<Long> ids = coreTreeService.findSysDepartmentIdByOrganizeId(organizeId);
                    departmentIdList.addAll(ids);
                }
            }
        }

        // 封装部门 ID 信息
        if(user.getDepartmentId() != null){
            SysDepartment department = departmentRDao.getById(user.getDepartmentId());
            departmentIdList.addAll(coreTreeService.findSysDepartmentChildIds(department));
        }

        List<Long> idList = findSysUserIdListByDepartmentId(departmentIdList);
        user.setDepartmentIdList(StringTool.getListString(idList));

        //生成hql查询语句
        String hqlPack = CoreHqlPack.packHqlSysUser(user);
        pager = PagerHelper.getPager(pager, sysUserRDao.findByHqlWhereCount(hqlPack));
        return new ListPager(sysUserRDao.findByHqlWherePage(hqlPack + user.orderBy(), pager), pager);
    }

    @Override
    @ApiOperation(value = "账号查询", notes = "根据ID 查询账号信息")
    public SysUser getSysUserById(Long id) {
        LOGGER.debug("平台用户 SYS_USER get By id :{}", id);
        return sysUserRDao.getById(id);
    }

    @Override
    @ApiOperation(value = "用户查询", notes = "根据ID 查询用户信息")
    public SysUserInfo getSysUserInfoById(Long id) {
        return sysUserInfoRDao.getByProperty("id",id);
    }

    @Override
    @ApiOperation(value = "账号查询", notes = "根据登录名查询用户信息")
    public SysUser getSysUserByLoginName(String loginName) {
        LOGGER.debug("平台用户 SYS_USER find By Login Name :{}", loginName);
        return sysUserRDao.getByProperty(new String[]{"userLoginName", "isValid"},
                new Object[]{loginName, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()});
    }

    @Override
    @ApiOperation(value = "账号查询", notes = "根据邮箱查询用户信息")
    public SysUser getSysUserByEmail(String email) {
        return sysUserRDao.getByProperty(new String[]{"userEmail", "isValid"},
                new Object[]{email, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()});
    }

    @Override
    @ApiOperation(value = "账号查询", notes = "根据手机号查询用户信息")
    public SysUser getSysUserByPhone(String phone) {
        return sysUserRDao.getByProperty(new String[]{"userPhone", "isValid"},
                new Object[]{phone, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()});
    }

    @Override
    @ApiOperation(value = "账号角色", notes = "根据账号ID查询账号角色关系")
    public List<SysRefUserRole> findSysRefUserRoleByUserId(Long userId) {
        return refUserRoleRDao.findByProperty("userId",userId);
    }

    @Override
    @ApiOperation(value = "检查-账号登录名", notes = "判断账号是否存在")
    public boolean checkSysUserLoginName(String userLoginName, long id) {
        int count = 0;
        if(id > 0){
            StringBuffer sw = new StringBuffer();
            HqlPack.getStringEqualPack(userLoginName,"userLoginName",sw);
            HqlPack.getNumNOEqualPack(id,"id",sw);
            count = sysUserRDao.findByHqlWhereCount(sw.toString());

        }else{
            count = sysUserRDao.findByPropertyCount("userLoginName",userLoginName);
        }
        return count <= 0 ;
    }

    @Override
    @ApiOperation(value = "检查-账号邮箱", notes = "判断邮箱是否存在")
    public boolean checkSysUserEmail(String email, long id) {
        int count;
        if(id > 0){
            StringBuffer sw = new StringBuffer();
            HqlPack.getStringEqualPack(email,"userEmail",sw);
            HqlPack.getNumNOEqualPack(id,"id",sw);
            count = sysUserRDao.findByHqlWhereCount(sw.toString());

        }else{
            count = sysUserRDao.findByPropertyCount("userEmail",email);
        }
        return count <= 0 ;
    }

    @Override
    @ApiOperation(value = "检查-账号手机", notes = "判断手机是否存在")
    public boolean checkSysUserPhone(String phone, long id) {
        int count;
        if(id > 0){
            StringBuffer sw = new StringBuffer();
            HqlPack.getStringEqualPack(phone,"userPhone",sw);
            HqlPack.getNumNOEqualPack(id,"id",sw);
            count = sysUserRDao.findByHqlWhereCount(sw.toString());

        }else{
            count = sysUserRDao.findByPropertyCount("userPhone",phone);
        }
        return count <= 0 ;
    }

    @Override
    @ApiOperation(value = "检查-账号唯一", notes = "账号唯一性校验")
    public void checkSysUserOnly(SysUser user) {
        if(user != null){
            // 登录名唯一教研
            if(!checkSysUserLoginName(user.getUserLoginName(), user.getId() == null ? 0 : user.getId())){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("用户名已存在")
                        .setErrorSolution("请重新输入用户名")
                        .build();
            }

            // 登录名唯一教研
            if(!checkSysUserEmail(user.getUserEmail(),user.getId() == null ? 0 : user.getId())){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("邮箱已存在")
                        .setErrorSolution("请重新输入邮箱")
                        .build();
            }

            // 登录名唯一教研
            if(!checkSysUserPhone(user.getUserPhone(),user.getId() == null ? 0 : user.getId())){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("手机号已存在")
                        .setErrorSolution("请重新输入手机号")
                        .build();
            }
        }
    }

    @Override
    @ApiOperation(value = "查询账户数量")
    public long getSysUserCount() {
        return sysUserRDao.listCount();
    }

    /**
     * 封装用户登陆信息
     *
     * @param sessionUser  当前会话信息
     * @param user         当前登录用户
     * @param userType     用户类型
     * @param languageCode 用户选择的语言
     * @return
     */
    @Override
    @ApiOperation(value = "封装用户信息",notes = "封装登录完成后的用户信息(角色、权限、部门、组织、岗位)")
    public SessionUser packSessionUser(SessionUser sessionUser, SysUser user, Integer userType, String languageCode) {
        LOGGER.debug("平台用户 SYS_USER user id :{}", user.getId());
        SysUserInfo userInfo = sysUserInfoRDao.getById(user.getUserInfoId());

        if(userInfo == null){
            throw new UnknownAccountException("用户信息不存在");
        }

        packSysUserRole(user);      //封装用户角色信息
        packSysUserMenu(user);      //封装用户功能信息
//        packSysUserMenuTree(sessionUser, user); //封装用户功能Tree信息
        packSysUserDepartment(user);    //封装用户部门信息
        packSysUserOrganize(user);                  //封装用户组织信息


        packSysUserInfoDepartment(userInfo);    //封装用户部门信息
        packSysUserInfoPosition(userInfo);      //封装用户岗位信息
        packSysUserInfoOrganize(userInfo);                  //封装用户组织信息

//        userInfo.setUser(user);
        sessionUser.setUserName(userInfo.getName());
        sessionUser.setUserCode(userInfo.getUserEmpNo());
        sessionUser.setUserId(userInfo.getId());
        sessionUser.setUserInfo(userInfo);

        sessionUser.setUserType(CommonEnumUtil.USER_TYPE.valueOf(userType));
        sessionUser.setLanguageCode(languageCode);
        sessionUser.setUser(user);

        return sessionUser;
    }

    /**
     * 账号数据排序
     *      创建时间 角色升序
     *      序号倒叙 + 编号升序       菜单
     *      创建时间 组织升序
     *      创建时间 部门升序
     * @param user
     */
    public void packSysUserSort(SysUser user){
        if(user != null){
            // 创建时间升序
            if(user.getRoleList() != null){
                user.getRoleList().sort(Comparator.comparing(SysRole::getCreateDatetime));
            }

            if(user.getMenuList() != null){
                user.getMenuList().sort(Comparator.comparing(SysMenu::getMenuSort).reversed() // 倒序
                                                    .thenComparing(SysMenu::getMenuCode));     //升序
            }

            if(user.getOrganizeList() != null){
                user.getOrganizeList().sort(Comparator.comparing(SysOrganize::getCreateDatetime));
            }

            if(user.getDepartmentList() != null){
                user.getDepartmentList().sort(Comparator.comparing(SysDepartment::getCreateDatetime));
            }
        }
    }

    /**
     *  用户数据排序
     *      岗位创建时间 升序
     *      部门创建时间 升序
     *      组织创建时间 升序
     * @param info
     */
    public void packSysUserInfoSort(SysUserInfo info){
        if(info != null){
            if(info.getPositionList() != null){
                info.getPositionList().sort(Comparator.comparing(SysPosition::getCreateDatetime));
            }
            if(info.getDepartmentList() != null){
                info.getDepartmentList().sort(Comparator.comparing(SysDepartment::getCreateDatetime));
            }
            if(info.getOrganizeList() != null){
                info.getOrganizeList().sort(Comparator.comparing(SysOrganize::getCreateDatetime));
            }
        }
    }

    /**
     * 封装用户角色信息
     * @param user
     * @return
     */
    public void packSysUserRole(SysUser user){
        List<SysRole> roleList = null;
        try {
            LOGGER.debug("平台用户 SYS_USER user id :{}", user.getUserInfoId());

            roleList = userPermissionDao.findSysRoleByUser(user);
        }catch (Exception e){
            LOGGER.error(" SysUser Peck Role information Error userId : {} Exception Message : {} " ,user.getUserInfoId(),e.getMessage());
            e.printStackTrace();
        }

        user.setRoleList(roleList);
    }

    /**
     * 封装用户 菜单信息
     * @param user
     * @return
     */
    public void packSysUserMenu(SysUser user){
        List<SysMenu> list = null;
        try {
            LOGGER.debug("平台用户 SYS_USER user id :{}", user.getUserInfoId());

            list = userPermissionDao.findSysMenuByUser(user);
        }catch (Exception e){
            LOGGER.error(" SysUser Peck Menu information Error userId : {} Exception Message : {} " ,user.getUserInfoId(),e.getMessage());
            e.printStackTrace();
        }

        user.setMenuList(list);
    }

//    /**
//     * 封装用户 菜单信息
//     * @param sessionUser
//     * @param user
//     * @return
//     */
//    public List<SysMenu> packSysUserMenuTree(SessionUser sessionUser, SysUser user){
//        List<SysMenu> list = null;
//        try {
//            LOGGER.debug("平台用户 SYS_USER user id :{}", user.getUserInfoId());
//            list = getSysMenuRootIds(user.getMenuList());
//            List<SysMenu> copyList = (List<SysMenu>) SerializeTool.deserialization(SerializeTool.serialization(user.getMenuList()));
//
//            if(list != null && list.size() > 0){
//                for (SysMenu menu : list) {
//                    coreTreeService.findMemSysMenuChildrenTreeByUserIdPack(menu,copyList,0);
////                    coreTreeService.findSysMenuChildrenTreeByUserIdPack(menu,user.getId(),0);
//                }
//            }
//        }catch (Exception e){
//            LOGGER.error(" SysUser Peck Menu Tree information Error userId : {} Exception Message : {} " ,user.getUserInfoId(),e.getMessage());
//            e.printStackTrace();
//        }
//
//        return list;
//    }

    /**
     * 封装用户 部门信息封装
     * @param userInfo
     * @return
     */
    public void packSysUserInfoDepartment(SysUserInfo userInfo){
        try {
            LOGGER.debug("平台用户 SYS_USER user id :{}", userInfo.getId());

             personnelService.findSysRefUserInfoDepartmentById(userInfo.id);

            userInfo.setDepartment(departmentRDao.getById(userInfo.getDepartmentId()));
            userInfo.setDepartmentList(personnelService.findSysUserInfoDepartmentByInfoId(userInfo.getId()));
        }catch (Exception e){
            LOGGER.error(" SysUser Peck Department information Error userId : {} Exception Message : {} " ,userInfo.getId(),e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 封装用户 部门信息封装
     * @param user
     * @return
     */
    public void packSysUserDepartment(SysUser user){
        try {
            LOGGER.debug("平台用户 SYS_USER user id :{}", user.getId());

            user.setDepartment(departmentRDao.getById(user.getDepartmentId()));
            user.setDepartmentList(personnelService.findSysUserDepartmentByInfoId(user.id));
        }catch (Exception e){
            LOGGER.error(" SysUser Peck Department information Error userId : {} Exception Message : {} " ,user.getId(),e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     *  封装用户 岗位信息封装
     * @param userInfo
     * @return
     */
    public void packSysUserInfoPosition(SysUserInfo userInfo){
        try {
            LOGGER.debug("平台用户 SYS_USER user id :{}", userInfo.getId());
            userInfo.setPositionList(userPermissionDao.findPositionByUser(userInfo));
            userInfo.setPosition(sysPositionRDao.getById(userInfo.getPositionId()));
        }catch (Exception e){
            LOGGER.error(" SysUser Peck Position information Error userId : {} Exception Message : {} " ,userInfo.getId(),e.getMessage());
        }
    }

    /**
     *  封装用户 组织信息封装
     * @param userInfo
     * @return
     */
    public void packSysUserInfoOrganize(SysUserInfo userInfo){
        try {
            LOGGER.debug("平台用户 SYS_USER user id :{}", userInfo.getId());
            userInfo.setOrganize(organizeRDao.getById(userInfo.getOrganizeId()));
            userInfo.setOrganizeList(personnelService.findSysUserInfoOrganize(userInfo.getId()));;
        }catch (Exception e){
            LOGGER.error(" SysUser Peck Organize information Error userId : {} Exception Message : {} " ,userInfo.getId(),e.getMessage());
        }
    }

    /**
     *  封装用户 组织信息封装
     * @param user
     * @return
     */
    public void packSysUserOrganize(SysUser user){
        try {
            LOGGER.debug("平台用户 SYS_USER user id :{}", user.getId());
            user.setOrganize(organizeRDao.getById(user.getOrganizeId()));
            user.setOrganizeList(personnelService.findSysUserOrganize(user.getId()));;
        }catch (Exception e){
            LOGGER.error(" SysUser Peck Organize information Error userId : {} Exception Message : {} " ,user.getId(),e.getMessage());
        }
    }

    /**
     * 获取集合中的Root Id
     * @param menus
     * @return
     */
    private List<SysMenu> getSysMenuRootIds(List<SysMenu> menus){
        Map<Long,SysMenu> map = new HashMap<>();
        List<SysMenu> result = new ArrayList<>();
        SysMenu parentMenu = null;

        // 获取所有顶级节点 ParentId 不存在的对象
        for (SysMenu menu : menus) {
            parentMenu = map.get(menu.getParentId());
            if(parentMenu == null){
                for (SysMenu sysMenu : menus) {
                    if(sysMenu.getId().longValue() == menu.getParentId().longValue()){
                        parentMenu = sysMenu;
                    }
                }
            }
            map.put(menu.getParentId(),parentMenu);
        }

        // 封装返回对象
        for (Long parentId : map.keySet()) {
            if(map.get(parentId) == null){
                for (SysMenu sysMenu : menus) {
                    if(sysMenu.getParentId().longValue() == parentId.longValue()){
                        result.add(sysMenu);
                    }
                }
            }
        }

        return result;
    }

}
