# SecuityServiceImpl.java

    package com.mycim.server.security.service;

    import com.alipay.sofa.runtime.api.annotation.SofaService;
    import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding;
    import com.fa.sesa.exception.Assert;
    import com.fa.sesa.exception.Errors;
    import com.fa.sesa.i18n.I18nUtils;
    import com.fa.sesa.i18n.Languages;
    import com.fa.sesa.threadlocal.LocalContext;
    import com.mycim.framework.jdbc.Page;
    import com.mycim.framework.logging.Logger;
    import com.mycim.framework.logging.LoggerFactory;
    import com.mycim.framework.utils.lang.ObjectUtils;
    import com.mycim.framework.utils.lang.StringUtils;
    import com.mycim.framework.utils.lang.collections.CollectionUtils;
    import com.mycim.framework.utils.lang.collections.MapUtils;
    import com.mycim.framework.utils.lang.math.NumberUtils;
    import com.mycim.framework.utils.lang.time.DateUtils;
    import com.mycim.server.base.manager.NamedObjectManager;
    import com.mycim.server.base.manager.RelationManager;
    import com.mycim.server.security.manager.*;
    import com.mycim.server.system.manager.LabelManager;
    import com.mycim.server.system.manager.ReferenceFileManager;
    import com.mycim.valueobject.MessageIdList;
    import com.mycim.valueobject.ObjectList;
    import com.mycim.valueobject.bas.NamedObject;
    import com.mycim.valueobject.bas.Relation;
    import com.mycim.valueobject.bas.RelationEventModle;
    import com.mycim.valueobject.bas.RelationHistory;
    import com.mycim.valueobject.consts.*;
    import com.mycim.valueobject.security.*;
    import com.mycim.valueobject.sys.ReferenceFileDetail;
    import com.mycim.valueobject.sys.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import javax.validation.constraints.NotNull;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author Johnson W
     */
    @Service
    @SofaService(interfaceType = SecurityService.class, bindings = {@SofaServiceBinding(bindingType = "bolt")})
    @Transactional
    public class SecuityServiceImpl implements SecurityService {

        private static final Logger logger = LoggerFactory.getLogger(SecuityServiceImpl.class);

        @Autowired
        private NamedObjectManager namedObjectManager;

        @Autowired
        private UserManager userManager;

        @Autowired
        private StationManager stationManager;

        @Autowired
        private MenuManager menuManager;

        @Autowired
        private ButtonManager buttonManager;

        @Autowired
        private ReferenceFileManager referenceFileManager;

        @Autowired
        private RelationManager relationManager;

        @Autowired
        private UserGroupManager userGroupManager;

        @Autowired
        private RoleManager roleManager;

        @Autowired
        private LabelManager labelManager;

        @Override
        public String[] getSecurityFlag(long userRRN, String namedSpace, String programID) {
            return new String[0];
        }

        @Override
        public Map getSecurityInfo(Long userRrn, String screenId) {
            return null;
        }

        @Override
        public Long checkPassword(String userId, String password, Long facility) {
            return userManager.checkPassword(userId, password, facility);
        }

        @Override
        public Long checkUserTime(Long userRrn, Long facility) {
            return null;
        }

        @Override
        public boolean checkRole(Long userRrn, Long instanceRrn, String key) {
            return false;
        }

        @Override
        public List<Map> getSecurityMenuListById(long menuRoot, Languages language, String id, String isLeaf) {
            return menuManager.getSecurityMenuListById(menuRoot, language, id, isLeaf);
        }

        @Override
        public List<Map> getAllRole() {
            return roleManager.getAllRoleInfo();
        }

        @Override
        public List<Map> getSecurityMenuList(long menuRoot, Languages language) {
            return menuManager.getSecurityMenuList(menuRoot, language);
        }

        @Override
        public List<Map<String, Object>> getSecurityMenuTreeRootList(long menuRoot, Languages language) {
            return menuManager.getSecurityMenuTreeRootList(menuRoot, language);
        }

        @Override
        public Collection getSecurityMenuTreeListById(long menuRoot, Languages language, String id) {
            return menuManager.getSecurityMenuTreeListById(language, id);
        }

        @Override
        public Collection getGrantSecurityMenuList(long roleRrn, Languages language) {
            return null;
        }

        @Override
        public Collection getMenuTree(long menuRoot, Languages language, String id) {
            return null;
        }

        @Override
        public Collection getMenuTreeRoot(long menuRoot, Languages language) {
            return null;
        }

        @Override
        public Collection getMenuTreeRootLeaf(long menuRoot, Languages language, String id) {
            return null;
        }

        @Override
        public long getUserMenuRrn(long useRrn) {
            return 0;
        }

        @Override
        public List<RelationHistory> getRelationHistory(Long fromRrn) {
            List<RelationHistory> relationHistory = relationManager.getRelationHistory(fromRrn);
            if (CollectionUtils.isEmpty(relationHistory)) {
                return null;
            }
            return relationHistory;
        }

        @Override
        public Collection getClassfication(Long treeRrn) {
            return null;
        }

        @Override
        public Collection getClassfication(String objectType, Long facility, Long instanceRrn) {
            return null;
        }

        @Override
        public void maintainClassfication(Long instanceRrn, String[] classValues) {

        }

        @Override
        public void maintainClassfication(Long instanceRrn, String[] classValues, String[] topClasses) {

        }

        @Override
        public Map getLotAttributes() {
            return null;
        }

        @Override
        public String getObjectAttributeValue(long instanceRrn, int instanceVersion, long fieldRrn) {
            return null;
        }

        @Override
        public void updateObjectAttributeValue(long instanceRrn, int instanceVersion, long fieldRrn, String value) {

        }

        @Override
        public Page searchResults(Page page, Map condtionMap, String buildSql) {
            return null;
        }

        @Override
        public List<Map> getRoleGrantMenu(long roleRrn) {
            List<Relation> relations = relationManager.getRelationsUseFromRrn(roleRrn, LinkTypeList.ROLE_MENU_KEY);
            List<Map> results = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(relations)) {
                for (Relation relation : relations) {
                    Map result = new HashMap();
                    result.put("torrn", relation.getToRrn());
                    result.put("fromrrn", relation.getAttributedata1());
                    results.add(result);
                }
            }
            return results;
        }

        @Override
        public List<Map> getUserGrantRoleList(long userRrn) {
            List<Relation> relations = relationManager.getRelationsUseFromRrn(userRrn, LinkTypeList.USER_ROLE_KEY);
            List<Map> results = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(relations)) {
                for (Relation relation : relations) {
                    Map result = new HashMap();
                    result.put("torrn", relation.getToRrn());
                    results.add(result);
                }
            }
            return results;
        }

        @Override
        public List<Long> getUserBelongUserGroup(long userRrn) {
            return userGroupManager.getUserBelongUserGroup(userRrn);
        }

        @Override
        public List<Map> getUserGroupGrantRoleList(long userGroupRrn) {
            List<Relation> relations = relationManager
                    .getRelationsUseFromRrn(userGroupRrn, LinkTypeList.USERGROUP_ROLE_KEY);
            List<Map> results = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(relations)) {
                for (Relation relation : relations) {
                    Map result = new HashMap();
                    result.put("torrn", relation.getToRrn());
                    result.put("fromrrn", relation.getFromRrn());
                    results.add(result);
                }
            }
            return results;
        }

        @Override
        public List<Map> getMenuFromRrn(long toRrn, long rootRrn) {
            return menuManager.getMenuFromRrn(toRrn, rootRrn);
        }

        @Override
        public boolean isExistedRelation(long subMenuRrn, long menuRrn) {
            return relationManager.isExistedRelation(subMenuRrn, menuRrn, LinkTypeList.MENU_SUBMENU_KEY);
        }

        @Override
        public boolean isExistedRelation(long menuRrn) {
            return relationManager.isExistedRelation(null, menuRrn, LinkTypeList.MENU_SUBMENU_KEY);
        }

        @Override
        public Collection getHasGrantUserGroupAll(long roleRrn, String userGroupId) {
            return roleManager.getHasGrantUserGroupAll(roleRrn, userGroupId);
        }

        @Override
        public Collection getHasRoleGrantUserAll(long roleRrn, String userId) {
            return roleManager.getHasRoleGrantUserAll(roleRrn, userId);
        }

        @Override
        public Collection getRoleGrantUserGroup(long roleRrn) {
            List<Relation> relations = relationManager.getRelationsUseToRrn(roleRrn, LinkTypeList.USERGROUP_ROLE_KEY);
            List<Map> results = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(relations)) {
                for (Relation relation : relations) {
                    Map result = new HashMap();
                    result.put("torrn", relation.getToRrn());
                    result.put("fromrrn", relation.getFromRrn());
                    result.put("attribute1", relation.getAttributedata1());
                    results.add(result);
                }
            }
            return results;
        }

        @Override
        public Collection getRoleGrantUser(long roleRrn) {
            List<Relation> relations = relationManager.getRelationsUseToRrn(roleRrn, LinkTypeList.USER_ROLE_KEY);
            List<Map> results = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(relations)) {
                for (Relation relation : relations) {
                    Map result = new HashMap();
                    result.put("torrn", relation.getToRrn());
                    result.put("fromrrn", relation.getFromRrn());
                    results.add(result);
                }
            }
            return results;
        }

        @Override
        public Collection getUserGroupById(String userGroupId) {
            return roleManager.getUserGroupByIdNotInRole(userGroupId);
        }

        @Override
        public Collection getUserGroupAll() {
            return userGroupManager.getAllUserGroupInfo();
        }

        @Override
        public List<Map> getUserAll() {
            return userManager.getAllUserInfo();
        }

        @Override
        public Collection getUserById(String userId, long roleRrn) {
            return roleManager.getUserByIdNotInRole(userId, roleRrn);
        }

        @Override
        public List<Map> getHasGrantUserAll(long userGroupRrn, String userId) {
            return userGroupManager.getHasGrantUserAll(userGroupRrn, userId);
        }

        @Override
        public List<Map> getGroupUserById(String userId, long userGroupRrn) {
            return userGroupManager.getUsersByIdExcludeUserGroup(userGroupRrn, userId);
        }

        @Override
        public List<Button> getAllButtons(Long menuRrn) {
            return buttonManager.getAllButtons(menuRrn);
        }

        @Override
        public void insertButtonMenuExt(Long buttonRrn, Long menuRrn) {
            buttonManager.insertButtonMenuExt(buttonRrn, menuRrn);
        }

        @Override
        public void updateButtonMenu(Long buttonRrn, Long menuRrn) {
            buttonManager.updateButtonMenu(buttonRrn, menuRrn);
        }

        @Override
        public void updateButton(Button button) {
            buttonManager.updateButton(button);
        }

        @Override
        public void deleteAllButtonRelation(Long buttonRrn) {
            buttonManager.deleteAllButtonRelation(buttonRrn);
        }

        @Override
        public void deleteButton(Button button) {
            buttonManager.deleteButton(button);
        }

        @Override
        public List<Map> getRoleButton(Long roleRrn) {
            return buttonManager.getRoleButton(roleRrn);
        }

        @Override
        public void updateRoleButtonRelation(Long roleRrn, List<Long> buttonsRrn) {
            buttonManager.updateRoleButtonRelation(roleRrn, buttonsRrn);
        }

        @Override
        public Map getButtonInfoWithRoles(Collection roleRrns, String buttonId) {
            return roleManager.getButtonInfoWithRoles(roleRrns, buttonId);
        }

        @Override
        public Collection<Long> getUserGrantUserGroupAllRole(Long userRrn) {
            return roleManager.getUserGrantUserGroupAllRole(userRrn);
        }

        @Override
        public String getButtonDesc(String buttonId, Long faciltyRrn) {
            return null;
        }

        @Override
        public boolean checkUserHasMenu(String userId, String menuId, Long facilityRrn) {
            return false;
        }

        @Override
        public long validUser(String userName, String password, long facility) {
            long flag = 0;
            if (userName != null && userName.equals("ADMIN")) {
                facility = 1;
            }

            String nameSpace = namedObjectManager.getNamedSpace(facility, ObjectList.USER_KEY);
            NamedObject namedObject = namedObjectManager.getNamedObject(userName, nameSpace, ObjectList.USER_KEY);
            if (namedObject == null) {
                return 0; // 用户不存在
            }

            long userRrn = namedObject.getInstanceRrn();
            boolean isExcited = checkPassword(userRrn, password);
            if (isExcited) {
                flag = userRrn; // 用户存在，并且密码匹配
            } else {
                flag = -1; // 用户存在，密码不匹配
            }

            return flag;
        }

        @Override
        public boolean checkPassword(long userRrn, String password) {
            boolean isExited = false;
            String dbPassword = userManager.getPassword(userRrn);
            if (StringUtils.isBlank(dbPassword)) {
                isExited = true;
            } else if ((dbPassword != null) && dbPassword.equals(password)) {
                isExited = true;
            }
            return isExited;
        }

        @Override
        public TreeDetail getTreeDetail(TreeDetail instance) {
            return null;
        }

        @Override
        public Role getRole(Role role) {
            NamedObject object = namedObjectManager.getNamedObject(role);
            if (object == null) {
                return null;
            }
            role.copyNamedObject(object);
            return role;
        }

        @Override
        public SecurityClass getSecurityClass(SecurityClass instance) {
            return null;
        }

        @Override
        public Menu getMenu(Menu menu) {
            return menuManager.getMenu(menu);
        }

        @Override
        public long insertTreeDetail(TreeDetail treeDetail) {
            return 0;
        }

        @Override
        public long insertMenu(Menu menu) {
            return menuManager.insertMenu(menu);
        }

        @Override
        public void deleteMenu(Menu instance) {
            menuManager.deleteMenuItem(instance);
        }

        @Override
        public long insertSecurityClass(SecurityClass securityClass) {
            return 0;
        }

        @Override
        public long insertRole(Role role) {
            return namedObjectManager.insertNamedObject(role);
        }

        @Override
        public Collection getRolesByObjectType(String objectType) {
            return null;
        }

        @Override
        public List<Menu> getSubMenus(long menuRrn) {
            return menuManager.getSubMenus(menuRrn);
        }

        @Override
        public Menu getParentMenu(long menuRrn) {
            return menuManager.getParentMenu(menuRrn);
        }

        @Override
        public Collection getTreeChilds(TreeDetail tree) {
            return null;
        }

        @Override
        public Collection getUserGroupsByRole(Role role) {
            return null;
        }

        @Override
        public void updateRole(Role role) {
            namedObjectManager.updateNamedObject(role);
        }

        @Override
        public void updateSecurityClass(SecurityClass instance) {

        }

        @Override
        public void updateMenu(Menu menu) {
            menuManager.updateMenu(menu);
        }

        @Override
        public void updateTreeDetail(TreeDetail instance) {

        }

        @Override
        public Collection getScreensBySecurityClass(SecurityClass aClass) {
            return null;
        }

        @Override
        public Collection getGroupsBySecurityClass(SecurityClass aClass) {
            return null;
        }

        @Override
        public User getUser(Long userRrn) {
            return userManager.getUser(userRrn);
        }

        @Override
        public User getUser(User user) {
            return userManager.getUser(user);
        }

        @Override
        public User getUserByLdapId(String ldapId) {
            return userManager.getUserByLdapId(ldapId);
        }

        @Override
        public boolean updatePassword(long userRrn, String newPwd) {
            return userManager.updatePassword(userRrn, newPwd);
        }

        @Override
        public Collection getUserWithGroupGrantRoleList(long userRrn) {
            List<Long> userRoles = userManager.getUserGrantRoleList(userRrn);
            List<Long> userGroupRoles = userManager.getUserGroupGrantRoleList(userRrn);
            userRoles.addAll(userGroupRoles);
            return CollectionUtils.removeDuplicate(userRoles);
        }

        @Override
        public void insertLoginLog(LoginLog loginlog) {

        }

        @Override
        public long getUserLastLoginTime(long userRrn) {
            return 0;
        }

        @Override
        public void changeUserStatus(long userRrn, String userStatus, String longinUserId) {
            userManager.changeUserStatus(userRrn, userStatus, longinUserId);
        }

        @Override
        public long getUserLastChangePasswordTime(long userInstanceRrn) {
            return 0;
        }

        @Override
        public UserGroup getUserGroup(UserGroup group) {
            return userGroupManager.getUserGroup(group);
        }

        @Override
        public void addUserToUsergroup(Relation relation) {
            relation.setLinkType(LinkTypeList.USER_USERGROUP_KEY);

            insertUserPermissions(relation);
        }

        @Override
        public long getRootMenuRrn(long facilityRrn) {
            return namedObjectManager
                    .getNamedObjectRrn("ROOTMENU", namedObjectManager.getNamedSpace(facilityRrn, ObjectList.MENU_KEY),
                                       ObjectList.MENU_KEY);
        }

        @Override
        public Map<String, Object> getUserAuthorizationMenu(long userRrn, long facilityRrn, Languages language) {
            // result.addAll(getUserMenu(userRrn, language)); //无用代码
            List<Map<String, Object>> result = new ArrayList<>(getRoleMenu(userRrn, facilityRrn, language));
            return filterMenu(facilityRrn, result);
        }

        @Override
        public String getUserType(User user) {
            // TODO:用于获取用户类型，PE/EE
            return "";
        }

        @Override
        public Station getStation(Station station) {
            return stationManager.getStation(station);
        }

        @Override
        public long insertStation(Station station) {
            return stationManager.insertStation(station);
        }

        @Override
        public long insertUser(User user) {
            return userManager.insertUser(user);
        }

        @Override
        public long insertUserGroup(UserGroup userGroup) {
            return userGroupManager.insertUserGroup(userGroup);
        }

        @Override
        public void deleteStation(Station station) {
            stationManager.deleteStation(station);
        }

        @Override
        public void deleteUser(User user) {
            userManager.deleteUser(user);
        }

        @Override
        public void deleteUserGroup(UserGroup userGroup) {
            userGroupManager.deleteUserGroup(userGroup);
        }

        @Override
        public void updateStation(Station station) {
            stationManager.updateStation(station);
        }

        @Override
        public void updateUser(User user) {
            userManager.updateUser(user);
        }

        @Override
        public void updateUserGroup(UserGroup userGroup) {
            userGroupManager.updateUserGroup(userGroup);
        }

        @Override
        public List<Relation> getUsers(UserGroup group) {
            return relationManager.getRelationsUseToRrn(group.getInstanceRrn(), LinkTypeList.USER_USERGROUP_KEY);
        }

        @Override
        public void removeUserFromGroup(Relation relation) {
            relation.setLinkType(LinkTypeList.USER_USERGROUP_KEY);

            deleteUserPermissions(relation);
        }

        @Override
        public void changeUserPassword(User user) {

        }

        @Override
        public boolean isNodeInTree(Long rootRrn, Long menuRrn) {
            return false;
        }

        @Override
        public void addSubMenuToMenu(Relation relation) {
            if (relationManager.getRelation(relation.getFromRrn(), relation.getToRrn(), relation.getLinkType()) == null) {
                relation.setSequenceNumber(0);
                relationManager.insertRelation(relation);
            }
        }

        @Override
        public void removeUserFromRole(Relation relation) {
            relation.setLinkType(LinkTypeList.USER_ROLE_KEY);

            setNecessaryParameters(relation,TransactionNames.DELETE_KEY);
            relationManager.deleteRelation(relation, DataBaseNames.REL_USER_PERMISSIONS, DataBaseNames.REL_USER_PERMISSIONS_H);
        }

        @Override
        public List<Relation> getUserRoles(long userRrn) {
            List<Relation> relations = relationManager.getRelationsUseFromRrn(userRrn, LinkTypeList.USER_ROLE_KEY);
            if (CollectionUtils.isNotEmpty(relations)) {
                for (Relation relation : relations) {
                    NamedObject object = namedObjectManager.getNamedObject(relation.getToRrn());
                    relation.copyNamedObject(object);
                }
            }
            return relations;
        }

        @Override
        public void addUserToRole(Relation relation) {
            relation.setLinkType(LinkTypeList.USER_ROLE_KEY);

            setNecessaryParameters(relation,TransactionNames.CREATE_KEY);
            relationManager.insertRelation(relation, DataBaseNames.REL_USER_PERMISSIONS, DataBaseNames.REL_USER_PERMISSIONS_H);
        }

        @Override
        public boolean isAdminGroup(long userGroupRrn) {
            return userGroupManager.isAdminGroup(userGroupRrn);
        }

        @Override
        public void updateRoleMenuBtnRelation(String userId, List<Relation> relations, long roleRrn) {
            roleManager.updateRoleMenuBtnRelation(userId, relations, roleRrn);
        }

        @Override
        public List<MenuTreeNode> getRootMenuTree(Long facilityRrn, Languages language) {
            long rootMenuRrn = getRootMenuRrn(facilityRrn);

            List<MenuTreeNode> userMenuTree = menuManager.getMenuTree(language, rootMenuRrn);
            if (CollectionUtils.isEmpty(userMenuTree)) {
                userMenuTree = Collections.emptyList();
            }

            return userMenuTree;
        }

        @Override
        public void deleteRole(Role role) {
            roleManager.deleteRole(role);
        }

        @Override
        public List<Map<String, Object>> qrySecuritySysParaSetTree(Long facilityRrn, Languages language) {
            long menuRootRrn = namedObjectManager.getNamedObjectRrn("ROOTMENU", facilityRrn, ObjectList.MENU_KEY);
            List<Map<String, Object>> menuTree = getSecurityMenuTreeRootList(menuRootRrn, language);
            List<Map> grantUserMenus = menuManager.getUserAccessMenuItemInfos(LocalContext.getUserRrn());
            List<Map<String, Object>> result = new ArrayList<>();
            for (Map<String, Long> map : grantUserMenus) {
                for (Map<String, Object> node : menuTree) {
                    boolean isGrantUserMenu = MapUtils.getLong(node, "torrn").equals(MapUtils.getLong(map, "MENURRN")) &&
                            MapUtils.getLong(node, "fromrrn").equals(MapUtils.getLong(map, "PARENTMENURRN"));
                    if (isGrantUserMenu) {
                        result.add(node);
                    }
                }
            }

            for (Iterator iterator = result.iterator(); iterator.hasNext(); ) {
                HashMap menuItem = (HashMap) iterator.next();
                String id = (String) menuItem.get("torrn");
                String type = (String) menuItem.get("objectType");
                Collection menu_tree_children = new ArrayList();
                if (type.equalsIgnoreCase("SUBMENU")) {
                    // 查询子菜单列表
                    menu_tree_children = getSecurityMenuTreeListById(menuRootRrn, language, id);
                    for (Iterator iterator_children = menu_tree_children.iterator(); iterator_children.hasNext(); ) {
                        HashMap menuItem_children = (HashMap) iterator_children.next();
                        String id_children = (String) menuItem_children.get("torrn");
                        String type_children = (String) menuItem_children.get("objectType");
                        Collection menu_tree_children_r = new ArrayList();
                        if (type_children.equalsIgnoreCase("SUBMENU")) {
                            menu_tree_children_r = getSecurityMenuTreeListById(menuRootRrn, language, id_children);
                            for (Iterator iterator_children_r = menu_tree_children_r.iterator(); iterator_children_r
                                    .hasNext(); ) {
                                HashMap menuItem_children_r = (HashMap) iterator_children_r.next();
                                String id_children_r = (String) menuItem_children_r.get("torrn");
                                String type_children_r = (String) menuItem_children_r.get("objectType");

                                Collection menu_tree_children_r_r = new ArrayList();
                                if (type_children_r.equalsIgnoreCase("SUBMENU")) {
                                    menu_tree_children_r_r = getSecurityMenuTreeListById(menuRootRrn, language,
                                                                                         id_children_r);
                                    for (Iterator iterator_children_r_r = menu_tree_children_r_r
                                            .iterator(); iterator_children_r_r.hasNext(); ) {
                                        HashMap menuItem_children_r_r = (HashMap) iterator_children_r_r.next();
                                        String id_children_r_r = (String) menuItem_children_r_r.get("torrn");
                                        String type_children_r_r = (String) menuItem_children_r_r.get("objectType");
                                        menuItem_children_r_r.put("leaf", new Boolean(true));
                                    }
                                    menuItem_children_r.put("children", menu_tree_children_r_r);
                                } else {
                                    menuItem_children_r.put("leaf", new Boolean(true));
                                }
                            }
                            menuItem_children.put("children", menu_tree_children_r);
                        } else {
                            menuItem_children.put("leaf", new Boolean(true));
                        }
                    }
                    menuItem.put("children", menu_tree_children);
                } else {
                    menuItem.put("leaf", new Boolean(true));
                    menuItem.put("children", new ArrayList());
                }
            }

            Collections.sort(result, new Comparator<Map<String, Object>>() {

                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    String seq1 = MapUtils.getString(o1, "seq");
                    String seq2 = MapUtils.getString(o2, "seq");
                    return NumberUtils.toInt(seq1) - NumberUtils.toInt(seq2);
                }

            });
            return result;
        }

        @Override
        public void addButton(Button button) {
            buttonManager.addButton(button);
        }

        @Override
        public List<Relation> getEquipmentOfStation(long stationRrn) {
            return stationManager.getEquipmentOfStation(stationRrn);
        }

        @Override
        public List<RelationEventModle> getEquipmentOfStation(long stationRrn, long eventRrn) {
            return stationManager.getEquipmentOfStation(stationRrn, eventRrn);
        }

        @Override
        public List<Relation> getOperationOfStation(long stationRrn) {
            return stationManager.getOperationOfStation(stationRrn);
        }

        @Override
        public List<Relation> getUserOfStation(long stationRrn) {
            return stationManager.getUserOfStation(stationRrn);
        }

        @Override
        public void addOperationToStation(Relation relation) {
            relation.setLinkType(LinkTypeList.STATION_OPER_KEY);

            insertStationRelation(relation);
        }

        @Override
        public void addUserToStation(Relation relation) {
            relation.setLinkType(LinkTypeList.STATION_USER_KEY);

            insertStationRelation(relation);
        }

        @Override
        public void removeEquipmentFromStation(Relation relation) {
            // get the transaction log
            relation.setLinkType(LinkTypeList.STATION_EQPT_KEY);

            // insert a relatin into the relation table

            removeStationRelation(relation);
        }

        @Override
        public void removeOperationFromStation(Relation relation) {
            relation.setLinkType(LinkTypeList.STATION_OPER_KEY);

            // insert a relatin into the relation table

            removeStationRelation(relation);
        }

        @Override
        public void removeUserFromStation(Relation relation) {
            relation.setLinkType(LinkTypeList.STATION_USER_KEY);
            // insert a relatin into the relation table

            removeStationRelation(relation);
        }

        @Override
        public List<Station> getStationsByEquips(long equipRrn) {
            return stationManager.getStationsByEquips(equipRrn);
        }

        @Override
        public User getUser(String userId, Long facilityRrn) {
            return userManager.getUser(userId, facilityRrn);
        }

        @Override
        public Collection<Long> getUserRoleList(Long userRrn) {
            List<Map> userGrantRole = getUserGrantRoleList(userRrn);
            Collection<Long> rolesRrn = getUserGrantUserGroupAllRole(userRrn);
            for (Object obj : userGrantRole) {
                Map map = (Map) obj;
                Long roleRrn = MapUtils.getLong(map, "torrn");
                rolesRrn.add(roleRrn);
            }
            return CollectionUtils.removeDuplicate(rolesRrn);

        }

        @Override
        public List<String> getDepartmentIds(String reference_file, String key_1_value, String get_Value_key) {
            return userGroupManager.getDepartmentIds(reference_file, key_1_value, get_Value_key);
        }

        @Override
        public boolean checkUserExistedUserGroups(Long userRrn, String groups) {
            return userGroupManager.checkUserExistedUserGroups(userRrn, groups);
        }

        @Override
        public boolean isHasBtnPermission(long userRrn, String btnId) {
            return MapUtils.isNotEmpty(getButtonInfoWithRoles(getUserWithGroupGrantRoleList(userRrn), btnId));
        }

        @Override
        public Boolean hasRelationEditPermission(Long facilityRrn, Long userRrn, Long engineerGroupRrn) {
            return roleManager.isAdminRole(facilityRrn, userRrn) ||
                    userGroupManager.getUserGroupRrnsByUserRrn(userRrn).contains(engineerGroupRrn);
        }

        @Override
        public List<Map> getUsers(String deptId) {
            return userManager.getUsers(deptId);
        }

        @Override
        public String getTel(String deptId, String userId) {
            return userManager.getTel(deptId, userId);
        }

        @Override
        public List<Relation> getUserGroups(long userRrn) {
            return userGroupManager.getUserGroups(userRrn);
        }

        @Override
        public List<Relation> getUserGroups(User user) {
            return getUserGroups(namedObjectManager.getNamedObjectRrn(user));
        }

        @Override
        public String getUserName(long userRrn) {
            return userManager.getUserName(userRrn);
        }

        @Override
        public Map getUserInfo4Alarm(long userRrn) {
            return userManager.getUserInfo4Alarm(userRrn);
        }

        @Override
        public Map getUserInfo4AlarmByUserGroup(long userGroupRrn) {
            return userManager.getUserInfo4AlarmByUserGroup(userGroupRrn);
        }

        @Override
        public Boolean isAdminRole(long facilityRrn, long userRrn) {
            return roleManager.isAdminRole(facilityRrn, userRrn);
        }

        @Override
        public Boolean isExportRole(long facilityRrn, long userRrn) {
            return roleManager.isExportRole(facilityRrn, userRrn);
        }

        @Override
        public List<UserGroup> getUserGroupByUserRrn(Long userRrn) {
            return userGroupManager.getUserGroupByUserRrn(userRrn);
        }

        @Override
        public List<User> getUserInfoForParam(Map param) {
            return userManager.getUserInfoForParam(param);
        }

        @Override
        public Page getInformUser(User user,Page page) {
            return  userManager.getInformUser(user, page);
        }

        @Override
        public Page getInformHistory(User user, Page page) {
            return userManager.getInformHistory(user,page);
        }

        @Override
        public void releaseOrCancelInformToUser(List<String> userRrnList, String informFlag) {
            User userInform = new User();
            for (String userRrn : userRrnList) {
                User user  = userManager.getInformUser(NumberUtils.toLong(userRrn));
                userInform.setInformFlag(informFlag);
                userInform.setInstanceRrn(NumberUtils.toLong(userRrn));
                if(user!=null){
                    if(StringUtils.equals(informFlag,Constants.INFORM_STATUS.NOT_INFORM)) {
                        userInform.setLastInformTime(user.getLastInformTime());
                    }
                    userManager.updateUserInform(userInform);
                } else {
                    userManager.insertUserInform(userInform);
                }
            }
        }

        @Override
        public Map<Long, String> getInformUserAndMsg(Long userRrn) {
            Map<Long, String> informMap = new HashMap<>();
            String nowTime = DateUtils.getNowTime();
            List<ReferenceFileDetail> referenceFileDetails = referenceFileManager.getRefFileValues(ReferenceDetailNames.SYSTEM_NOTICE, LocalContext.getFacilityRrn());
            Map<String,String> refMap =
                    referenceFileDetails.stream().collect(
                            Collectors.toMap(ReferenceFileDetail::getKey1Value, ReferenceFileDetail::getData1Value));
            String date = MapUtils.getString(refMap, "MSGDATE");
            String content = MapUtils.getString(refMap, "MSGCONTENT");
            String title = MapUtils.getString(refMap, "MSGTITLE");
            String time = MapUtils.getString(refMap, "MSGTIME");
            // 判断是否在有效期内
            boolean flag = DateUtils.parse(time,DateUtils.DATE_FORMAT).getTime() < DateUtils.parse(nowTime,DateUtils.DATE_FORMAT).getTime()
                            && DateUtils.parse(nowTime,DateUtils.DATE_FORMAT).getTime() < DateUtils.parse(date,DateUtils.DATE_FORMAT).getTime();
            StringBuilder stringBuilder = new StringBuilder();
            User user = userManager.getInformUser(userRrn);
            if(user!= null && StringUtils.equalsIgnoreCase(user.getInformFlag(),Constants.INFORM_STATUS.INFORM) && flag){
                if(StringUtils.isBlank(DateUtils.formatDate(user.getLastInformTime()))){
                    user.setLastInformTime(DateUtils.parse(nowTime));
                    userManager.updateLastInformTime(user);
                    stringBuilder.append(title).append("##").append(content).append("##").append(date);
                } else {
                    //判断今天是否通知过
                    Date nowDate = DateUtils.parse(nowTime,DateUtils.DATE_FORMAT4DAY);
                    if(nowDate.compareTo(user.getLastInformTime())==1) {
                        user.setLastInformTime(DateUtils.parse(nowTime));
                        userManager.updateLastInformTime(user);
                        stringBuilder.append(title).append("##").append(content).append("##").append(date);
                    }
                }
            }
            stringBuilder.append("##msg");
            informMap.put(userRrn,stringBuilder.toString());
            return informMap;
        }

        @Override
        public Page getRelationOfStation(Page page, String linType, long stationRrn) {
            return stationManager.getRelationOfStation(page, linType, stationRrn);
        }

        @Override
        public void addEquipmentToStation(Relation relation) {
            relation.setLinkType(LinkTypeList.STATION_EQPT_KEY);
            // relationManager.insertRelation(relation);
            insertStationRelation(relation);
        }

        @Override
        public void addRoleRelation(Relation relation) {
            relation.setSequenceNumber(0);
            insertUserPermissions(relation);
        }

        @Override
        public void deleteRoleRelation(Relation relation) {
            deleteUserPermissions(relation);
        }

        private List<Map<String, Object>> getRoleMenu(long userRrn, long facilityRrn, Languages language) {
            List<Map<String, Object>> result = new ArrayList<>();

            long rootMenuRrn = this.getRootMenuRrn(facilityRrn);
            List<MenuTreeNode> menuTree = menuManager.getMenuTree(language, rootMenuRrn);
            List<Map> grantUserMenus = menuManager.getUserAccessMenuItemInfos(userRrn);

            for (Map map : grantUserMenus) {
                for (MenuTreeNode node : menuTree) {
                    boolean isGrantUserMenu = node.getMenuRrn().equals(MapUtils.getLong(map, "MENURRN")) &&
                            node.getParentMenuRrn().equals(MapUtils.getLong(map, "PARENTMENURRN"));
                    if (isGrantUserMenu) {
                        result.add(convertNode2Map(node));
                    }
                }
            }

            return result;
        }

        @Deprecated
        private List<Map<String, Object>> getUserMenu(long userRrn, Languages language) {
            List<Map<String, Object>> result = new ArrayList<>();
            long rootMenuRrn = userManager.getUser(userRrn).getMenuRrn().longValue();
            if (rootMenuRrn != 0) {
                List<MenuTreeNode> userMenuTree = menuManager.getMenuTree(language, rootMenuRrn);
                if (CollectionUtils.isNotEmpty(userMenuTree)) {
                    for (MenuTreeNode node : userMenuTree) {
                        result.add(convertNode2Map(node));
                    }
                }
            }
            return result;
        }

        private Map<String, Object> convertNode2Map(@NotNull MenuTreeNode node) {
            Map<String, Object> map = new HashMap<>();
            map.put("menuId", node.getMenuId());
            map.put("id", node.getLabelId());
            map.put("icon", node.getIcon());
            map.put("text", node.getLabelText());
            map.put("torrn", node.getMenuRrn());
            map.put("fromrrn", node.getParentMenuRrn());
            map.put("program", node.getUrl());
            map.put("seq", node.getSequence());
            map.put("label", node.getLabelText());
            map.put("leaf", node.getIsLeafNode());
            map.put("labelId", node.getLabelId());
            map.put("url", node.getUrl());
            return map;
        }

        private List<Map<String, Object>> buildListOfDeletedDuplicateMenu(List<Map<String, Object>> list) {
            List<String> norepelist = new ArrayList<>();
            String uniqueValue;
            List<Map<String, Object>> repelist = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                uniqueValue = MapUtils.getString(map, "torrn") + "#" + MapUtils.getString(map, "fromrrn");
                if (!norepelist.contains(uniqueValue)) {
                    norepelist.add(uniqueValue);
                } else {
                    list.remove(i);
                    i--;
                    repelist.add(map);
                }
            }
            return list;
        }

        private Map<String, Object> filterMenu(long facilityRrn, List<Map<String, Object>> menuList) {
            List<String> lotLocationMenuButtonIds = getLotLocationMenuButtonIds(facilityRrn);
            List<String> menuListFilterMenuIds = getMenuListFilterMenuIds(facilityRrn);

            List<Map<String, Object>> willRemovedMenuList = new ArrayList<>();
            List<Map<String, Object>> filterMenuList = new ArrayList<>();
            Set<String> buttonSet = new HashSet<>();
            List<String> buttonData = new ArrayList<>();

            for (Map<String, Object> menuMap : menuList) {
                String menuId = MapUtils.getString(menuMap, "menuId");
                for (String lotLocationMenuButtonId : lotLocationMenuButtonIds) {
                    if (lotLocationMenuButtonId.equals(menuId)) {       //如果用户的权限中有此Button的权限
                        if (!"MENU_FUTURE_PROCESS".equals(menuId))      // MENU_FUTURE_PROCESS 菜单会在批次作业和菜单树上同时显示
                            willRemovedMenuList.add(menuMap);           //将此按钮的权限从菜单树上删掉
                        if (buttonSet.add(lotLocationMenuButtonId))
                            buttonData.add(lotLocationMenuButtonId);    //因为只需要展示在LotInfo界面
                        break;
                    }
                }

                for (String filterMenuId : menuListFilterMenuIds) {
                    if (filterMenuId.equals(menuId)) {
                        filterMenuList.add(menuMap);
                        break;
                    }
                }
            }

            menuList.removeAll(willRemovedMenuList);
            menuList.removeAll(filterMenuList);

            menuList.sort(Comparator.comparingInt(o -> NumberUtils.toInt(MapUtils.getString(o, "seq"))));

            Map<String, Object> results = new HashMap<>();
            results.put("menuData", menuList);
            results.put("buttonData", buttonData);
            return results;
        }

        /**
         * 获取LotLocation中对应按钮的菜单项
         *
         * @param facilityRrn
         * @return
         */
        private List<String> getLotLocationMenuButtonIds(long facilityRrn) {
            List<String> menuButtonIds = new ArrayList<>();
            long refrenceFileRrn = namedObjectManager
                    .getNamedObjectRrn("$$MENU_BTN_JOBBYLOT", facilityRrn, ObjectList.REFERENCE_FILE_KEY);
            if (refrenceFileRrn > 0) {
                menuButtonIds = menuManager.getMenusByRefrenceFileRrn(refrenceFileRrn);
            }
            return menuButtonIds;
        }

        /**
         * 获取左侧菜单列表需要过滤的菜单项
         *
         * @param facilityRrn
         * @return
         */
        private List<String> getMenuListFilterMenuIds(long facilityRrn) {
            List<String> menuButtonIds = new ArrayList<>();
            long refrenceFileRrn = namedObjectManager
                    .getNamedObjectRrn("$FILTER_LEFT_MENU_BY_BUTTON", facilityRrn, ObjectList.REFERENCE_FILE_KEY);
            if (refrenceFileRrn > 0) {
                menuButtonIds = menuManager.getMenusByRefrenceFileRrn(refrenceFileRrn);
            }
            return menuButtonIds;
        }

        /**
         * 如菜单树中有LotLocation菜单项，那将在菜单树中隐藏LotLocation中对应按钮的菜单项 this.getLotLocationMenuButtonIds()<br>
         * <br>
         * Redmine #14146: as recode the whole part of related code could have problematic consequences. therefore
         * only add this patch for both of the original entry request and the integrated entry request to properly
         * filter the menus;
         *
         * @param menuURL
         * @return
         */
        private boolean hasLotLocation(String menuURL) {
            String lotLocationActionURL = "lotLocation4CSECAction.do?qry=lotlocation&nav=true";
            String lotLocationPageURL = "wip/viewlotlocation4CSEC.jsp";
            return lotLocationActionURL.equals(menuURL) || lotLocationPageURL.equals(menuURL);
        }

        private void insertUserPermissions(Relation relation) {
            setNecessaryParameters(relation, TransactionNames.CREATE_KEY);
            relationManager.insertRelation(relation, DataBaseNames.REL_USER_PERMISSIONS, DataBaseNames.REL_USER_PERMISSIONS_H);
        }

        private void deleteUserPermissions(Relation relation) {
            setNecessaryParameters(relation, TransactionNames.DELETE_KEY);
            relationManager.deleteRelation(relation, DataBaseNames.REL_USER_PERMISSIONS, DataBaseNames.REL_USER_PERMISSIONS_H);
        }

        private void insertStationRelation(Relation relation) {
            setNecessaryParameters(relation, TransactionNames.CREATE_KEY);
            relationManager.insertRelation(relation, DataBaseNames.REL_STATION, DataBaseNames.REL_STATION_H);
        }

        private void removeStationRelation(Relation relation) {
            setNecessaryParameters(relation, TransactionNames.DELETE_KEY);
            relationManager.deleteRelation(relation, DataBaseNames.REL_STATION, DataBaseNames.REL_STATION_H);
        }

        private void setNecessaryParameters(Relation relation, String type) {
            if (StringUtils.isBlank(relation.getTransId())){
                relation.setTransId(type);
            }
            if (StringUtils.isBlank(relation.getTransPerformedby())){
                relation.setTransPerformedby(LocalContext.getUserId());
            }
        }

        @Override
        public void saveOrUpdateMenuRelation(Menu menu, HashMap<String, Object> menuInfoParams) {
            String menuId = MapUtils.getString(menuInfoParams, "menuId");
            String labelId = MapUtils.getString(menuInfoParams, "labelId");
            String instanceId = MapUtils.getString(menuInfoParams, "instanceId");
            String instanceDesc = MapUtils.getString(menuInfoParams, "instanceDesc");
            Long parentMenuRrn = MapUtils.getLong(menuInfoParams, "parentMenuRrn");
            String userId = LocalContext.getUserId();
            long menuRrn = menu.getInstanceRrn();

            // label 处理
            Label label = processLabel(labelId, instanceId, instanceDesc);
            // 标签内容
            processLabelItem(instanceDesc, label);
            // menu 处理
            processMenu(menu, label, parentMenuRrn, menuId);

            Relation relation = new Relation();
            relation.setTransId(TransactionNames.CREATE_KEY.toLowerCase());
            relation.setTransPerformedby(LocalContext.getUserId());
            if (ObjectUtils.isNotEmpty(parentMenuRrn) && parentMenuRrn != 0) {
                relation.setFromRrn(parentMenuRrn);
            } else {
                relation.setFromRrn(this.getRootMenuRrn(LocalContext.getFacilityRrn()));
            }
            relation.setToRrn(menu.getInstanceRrn());
            relation.setLinkType(LinkTypeList.MENU_SUBMENU_KEY);

            Relation relationInfo = relationManager.getRelation(relation.getFromRrn(), relation.getToRrn(), relation.getLinkType());
            if (ObjectUtils.isNotEmpty(relationInfo)) {
                return;
            }
            Assert.state(!this.isNodeInTree(relation.getToRrn(), relation.getFromRrn()),
                           Errors.create().key(MessageIdList.MENU_FORBID_ADD).content("无法添加此菜单!").build());

            if (ObjectUtils.isEmpty(relationManager.getRelation(relation.getFromRrn(), relation.getToRrn(), relation.getLinkType()))) {
                relation.setSequenceNumber(0);
                relationManager.insertRelation(relation);
            }

            // add by liran 勾选Program类型菜单的所有父菜单勾选框的业务逻辑
            List<Map> roles = roleManager.getAllRoleInfo();
            for (Map role: roles) {
                Long roleRrn = MapUtils.getLong(role, "instanceRrn");
                List<Map> roleGrantMenuList = getRoleGrantMenu(MapUtils.getLong(role, "instanceRrn"));
                // 判断菜单是否被角色授权
                boolean isGrantUserMenu = false;
                for (Map roleGrantMenu: roleGrantMenuList) {
                    if (MapUtils.getLong(roleGrantMenu, "torrn", 0L).equals(menuRrn)) {
                        isGrantUserMenu = true;
                        break;
                    }
                }

                if (isGrantUserMenu) {
                    ArrayList<Relation> relationList = new ArrayList<Relation>();
                    List<Relation> relations = relationManager.getParentMenuRelationsByRrn(menuRrn);
                    // 过滤老数据
                    for (Relation tempRelation: relations) {
                        Menu tempMenu = menuManager.getMenu(tempRelation.getFromRrn());
                        if (!ObjectUtils.isEmpty(tempMenu)) {
                            relationList.add(tempRelation);
                        }
                    }
                    // 将被挪动菜单的所有父菜单都勾选上
                    for (Relation menuNode: relationList) {
                        Relation parentRelation = new Relation();
                        parentRelation.setTransId(TransactionNames.CREATE_KEY.toLowerCase());
                        parentRelation.setLinkType(LinkTypeList.ROLE_MENU_KEY);
                        parentRelation.setFromRrn(roleRrn);
                        parentRelation.setAttributedata1(String.valueOf(menuNode.getFromRrn()));
                        parentRelation.setToRrn(menuNode.getToRrn());
                        parentRelation.setTransPerformedby(userId);
                        if (ObjectUtils.isEmpty(relationManager.getRelation(roleRrn, menuNode.getToRrn(), LinkTypeList.ROLE_MENU_KEY))) {
                            relationManager.insertRelation(parentRelation, DataBaseNames.REL_USER_PERMISSIONS, DataBaseNames.REL_USER_PERMISSIONS_H);
                        }
                    }
                    // 修改被挪动的Program类型菜单关联关系
                    Relation sonRelation = new Relation();
                    sonRelation.setLinkType(LinkTypeList.ROLE_MENU_KEY);
                    sonRelation.setFromRrn(roleRrn);
                    sonRelation.setTransPerformedby(userId);
                    sonRelation.setTransId(TransactionNames.MODIFY_KEY.toLowerCase());
                    sonRelation.setToRrn(menuRrn);
                    sonRelation.setAttributedata1(String.valueOf(parentMenuRrn));
                    sonRelation.setSequenceNumber(relationManager.getRelation(roleRrn, menuRrn, LinkTypeList.ROLE_MENU_KEY).getSequenceNumber());
                    relationManager.updateRelation(sonRelation);
                    relationManager.updateSpecificRelationTable(sonRelation, DataBaseNames.REL_USER_PERMISSIONS, DataBaseNames.REL_USER_PERMISSIONS_H, null);
                }
            }
        }

        @Override
        public Collection<Role> getUserRoleListWithGroupGrant(long userRrn) {
            List<Role> userRoles = userManager.getUserGrantRoles(userRrn);
            List<Role> userGroupRoles = userManager.getUserGroupGrantRoles(userRrn);
            userRoles.addAll(userGroupRoles);
            return CollectionUtils.removeDuplicate(userRoles);
        }

        @Override
        public List<Long> getUserGroupRrnsByUserRrn(Long userRrn) {
            return userGroupManager.getUserGroupRrnsByUserRrn(userRrn);
        }

        @Override
        public String getProcessRrnWithPermission(long userRrn) {
            return userGroupManager.getProcessRrnWithPermission(userRrn);
        }

        protected void process(NamedObject instance) {
            String action = instance.getTransId();

            if (action.equals(TransactionNames.CREATE_KEY.toLowerCase())) {
                long instanceRrn = 0;
                if (instance instanceof Label) {
                    instanceRrn = labelManager.insertLabel((Label) instance);
                } else if (instance instanceof Menu) {
                    instanceRrn = this.insertMenu((Menu) instance);
                }
                instance.setInstanceRrn(instanceRrn);
            } else if (action.equals(TransactionNames.DELETE_KEY.toLowerCase())) {
                if (instance instanceof Label) {
                    labelManager.deleteLabel((Label) instance);
                } else if (instance instanceof Menu) {
                    this.deleteMenu((Menu) instance);
                }
            } else if (action.equals(TransactionNames.MODIFY_KEY.toLowerCase())) {
                if (instance instanceof Label) {
                    labelManager.updateLabel((Label)instance);
                } else if (instance instanceof Menu) {
                    this.updateMenu((Menu) instance);
                }
            }

        }

        private Label processLabel(String labelId, String instanceId, String instanceDesc) {
            String labelName = StringUtils.trimToUpperCase(labelId);
            String autoLabelId = null;

            if (StringUtils.isNotBlank(labelName)) {
                autoLabelId = labelName;
            } else {
                if (StringUtils.isNotBlank(instanceId)) {
                    autoLabelId = Constants.PREFIX.LBL + StringUtils.UNDERLINE + StringUtils.trimToUpperCase(StringUtils.substringAfter(instanceId, StringUtils.UNDERLINE));
                }
            }

            // 标签
            Label label = new Label(autoLabelId, namedObjectManager.getNamedSpace(LocalContext.getFacilityRrn(), ObjectList.LABEL_KEY),
                                    ObjectList.LABEL_KEY);
            long labelRrn = namedObjectManager.getNamedObjectRrn(label);
            label.setTransPerformedby(LocalContext.getUserId());
            if (labelRrn <= 0) {
                label.setInstanceId(autoLabelId);
                label.setInstanceDesc(instanceDesc);
                label.setObjectType("NONE");
                label.setTransId(TransactionNames.CREATE_KEY.toLowerCase());
            } else {
                label.setInstanceRrn(labelRrn);
                label.setTransId(TransactionNames.MODIFY_KEY.toLowerCase());
            }
            this.process(label);

            return label;
        }

        private void processLabelItem(String instanceDesc, Label label) {
            LabelItem labelItem = new LabelItem();
            labelItem.setText(instanceDesc);
            labelItem.setLanguage(I18nUtils.getCurrentLanguage().toString());
            labelManager.updateLabelItem(label.getInstanceRrn(), labelItem);
        }

        private void processMenu(Menu menu, Label label, Long parentMenuRrn, String menuId) {
            // menu 处理
            long instanceRrn = menu.getInstanceRrn();
            if (instanceRrn <= 0) {
                menu.setInstanceId(menuId);
                menu.setTransId(TransactionNames.CREATE_KEY.toLowerCase());
            } else {
                menu.setTransId(TransactionNames.MODIFY_KEY.toLowerCase());
                this.deleteMenuRelation(instanceRrn, parentMenuRrn);
            }
            menu.setLabelRrn(label.getInstanceRrn());
            menu.setTransPerformedby(LocalContext.getUserId());
            this.process(menu);
            menu.setInstanceRrn(namedObjectManager.getNamedObjectRrn(menu));
            if (menu.getTransId().equals(TransactionNames.CREATE_KEY.toLowerCase()) && ObjectUtils.isNotEmpty(parentMenuRrn)) {
                boolean isExisted = this.isExistedRelation(parentMenuRrn, menu.getInstanceRrn());
                Assert.state(!isExisted, Errors.create().key(MessageIdList.MENU_ID_ALREADY_EXISTS).content(
                        "This menu id already exists in the parent menu.：{},You " + "can" + "'t add!")
                                              .args(menu.getInstanceId()).build());
            }
        }

        private void deleteMenuRelation(long menuRrn, Long parentMenuRrn) {
            List<Relation> results = relationManager.getRelationsUseToRrn(menuRrn, LinkTypeList.MENU_SUBMENU_KEY);

            for (Relation relation : results) {
                if (!relation.getFromRrn().equals(parentMenuRrn)) {
                    relation.setTransId(TransactionNames.DELETE_KEY.toLowerCase());
                    relationManager.deleteRelation(relation);
                }
            }
        }

    }