package com.crm.manager.service.impl;

import com.crm.manager.dao.mapper.UserRoleMapper;
import com.crm.manager.service.*;
import com.crm.rely.backend.core.constant.ManagerConstant;
import com.crm.manager.dao.repository.SysActionRepository;
import com.crm.manager.dao.repository.UserRoleRepository;
import com.crm.rely.backend.core.dto.user.role.UserActionDisplayDto;
import com.crm.rely.backend.core.dto.user.role.UserAllRoleDto;
import com.crm.rely.backend.core.dto.user.role.UserNodeDisplayDto;
import com.crm.rely.backend.core.dto.user.role.UserRoleDto;
import com.crm.rely.backend.core.entity.tenant.info.TenantEntity;
import com.crm.rely.backend.core.entity.user.role.*;
import com.crm.rely.backend.core.pojo.table.*;
import com.crm.rely.backend.core.pojo.view.SysNodeView;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.RoleConstants;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.FormatPage;
import com.crm.rely.backend.util.GetRandom;
import com.crm.rely.backend.util.ValidateUtil;
import com.google.common.base.Strings;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author houn
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleRepository userRoleRepository;

//    @Autowired
//    private SellerInfoDao sellerInfoDao;

    @Autowired
    private UserRoleNodeService userRoleNodeService;

    @Autowired
    private UserRoleDetailService userRoleDetailService;

    @Autowired
    private SysActionRepository userActionRepository;

    @Autowired
    private RedisService redisService;

    @Autowired
    private AuthorityService authorityService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 获取角色权限信息
     *
     * @param roleId
     * @return
     * @throws ServiceException
     */
    @Override
    public List<UserNodeDisplayDto> getUserNodeDisplay(Long roleId) throws ServiceException {
        /*
         *  查询服务器中是否已存在角色信息
         */
        String key = null;
        String roleUpdateRedisAuthorityIdentificationKey;
        if (roleId == null || roleId == 0) {
            key = RoleConstants.ROLE_USER_NODE + RoleConstants.ROLE_ADMIN;
            roleUpdateRedisAuthorityIdentificationKey = Constants.UPDATE_REDIS_AUTHORITY_IDENTIFICATION + "_" + RoleConstants.ROLE_ADMIN;
        } else {
            key = RoleConstants.ROLE_USER_NODE + roleId;
            roleUpdateRedisAuthorityIdentificationKey = Constants.UPDATE_REDIS_AUTHORITY_IDENTIFICATION + "_" + roleId;
        }
        //获取更新标识
        String updateRedisAuthorityIdentification = redisService.getObject(Constants.UPDATE_REDIS_AUTHORITY_IDENTIFICATION);
        if (Strings.isNullOrEmpty(updateRedisAuthorityIdentification)) {
            updateRedisAuthorityIdentification = authorityService.updateRedisAuthorityIdentification();
        }
        //获取角色更新标识
        String roleUpdateRedisAuthorityIdentification = redisService.getObject(roleUpdateRedisAuthorityIdentificationKey);
        //判断更新标识是否存在 如果不存在或者存在且和角色更新标识相同的话 直接从redis中获取权限
        if (!Strings.isNullOrEmpty(roleUpdateRedisAuthorityIdentification) && updateRedisAuthorityIdentification.equals(roleUpdateRedisAuthorityIdentification)) {
            if (redisService.hasKey(key)) {
                List<UserNodeDisplayDto> userNodeDisplayDtos = redisService.getObject(key);
                if (userNodeDisplayDtos.size() != 0) {
                    return userNodeDisplayDtos;
                }
            }
        }
        List<UserNodeDisplayDto> result = updateUserNode(roleId);
        //更新角色更新标识
        redisService.saveObject(roleUpdateRedisAuthorityIdentificationKey, updateRedisAuthorityIdentification);
        return result;
    }

    /**
     * 判断角色是否存在
     *
     * @param roleId
     * @throws ServiceException
     */
    @Override
    public void existRole(Long roleId) throws ServiceException {

        boolean existRole = userRoleRepository.existsById(roleId);
        if (!existRole) {
            throw new ServiceException(ManagerConstant.ROLE_NOT_EXIST_ERROR);
        }
    }

    /**
     * 添加角色
     *
     * @param userRoleAddEntity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addRoleInfo(UserRoleAddEntity userRoleAddEntity) throws ServiceException {
        if (userRoleRepository.existsByName(userRoleAddEntity.getName())) {
            throw new ServiceException("该角色名已存在");
        }

        UserRoleTable userRoleTable = new UserRoleTable();

        BeanUtils.copyProperties(userRoleAddEntity, userRoleTable);
        userRoleTable.setNumber(0);
        userRoleTable = userRoleRepository.saveAndFlush(userRoleTable);

        UserRoleOperateListEntity sellerRoleOperateListEntity = new UserRoleOperateListEntity();
        sellerRoleOperateListEntity.setModifyUser(userRoleAddEntity.getAddUser());
        sellerRoleOperateListEntity.setModifyTime(userRoleAddEntity.getAddTime());
        sellerRoleOperateListEntity.setModifyIp(userRoleAddEntity.getAddIp());
        sellerRoleOperateListEntity.setDepartmentId(userRoleAddEntity.getDepartmentId());
        sellerRoleOperateListEntity.setRoleId(userRoleTable.getId());
        sellerRoleOperateListEntity.setIsMerchantRole(userRoleAddEntity.getIsMerchantRole());
        sellerRoleOperateListEntity.setData(userRoleAddEntity.getData());
        sellerRoleOperateListEntity.setMerchantId(userRoleAddEntity.getMerchantId());
        updateRoleInfo(sellerRoleOperateListEntity);
    }

    /**
     * 修改角色信息
     *
     * @param userRoleUpdateEntity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleInfo(UserRoleUpdateEntity userRoleUpdateEntity) throws ServiceException {

        UserRoleTable userRoleTable = userRoleRepository.findOne(userRoleUpdateEntity.getId());
        if (userRoleTable == null) {
            throw new ServiceException(Constants.INFO_NOT_FOUND);
        }
        if (!userRoleTable.getName().equals(userRoleUpdateEntity.getName())) {
            if (userRoleRepository.existsByName(userRoleUpdateEntity.getName())) {
                throw new ServiceException("该角色名已存在");
            }
        }

        BeanUtils.copyProperties(userRoleUpdateEntity, userRoleTable);

        userRoleRepository.save(userRoleTable);

        UserRoleOperateListEntity userRoleOperateListEntity = new UserRoleOperateListEntity();
        userRoleOperateListEntity.setModifyUser(userRoleUpdateEntity.getModifyUser());
        userRoleOperateListEntity.setModifyTime(userRoleUpdateEntity.getModifyTime());
        userRoleOperateListEntity.setModifyIp(userRoleUpdateEntity.getModifyIp());
        userRoleOperateListEntity.setRoleId(userRoleTable.getId());
        userRoleOperateListEntity.setData(userRoleUpdateEntity.getData());
        updateRoleInfo(userRoleOperateListEntity);
    }

    /**
     * 修改权限
     *
     * @param userRoleOperateListEntity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleInfo(UserRoleOperateListEntity userRoleOperateListEntity) throws ServiceException {

        if (userRoleOperateListEntity == null) {
            return;
        }
        if (!userRoleRepository.existsById(userRoleOperateListEntity.getRoleId())) {
            throw new ServiceException("当前角色不可修改!!!");
        }
        Long roleId = userRoleOperateListEntity.getRoleId();
        List<UserRoleNodeTable> roleNodeTables = null;
        List<UserRoleDetailTable> roleDetailTables = null;
        List<UserRoleOperateEntity> userRoleOperateEntities = userRoleOperateListEntity.getData();
        if (userRoleOperateEntities != null && userRoleOperateEntities.size() > 0) {
            roleNodeTables = new ArrayList<>();
            roleDetailTables = new ArrayList<>();

            for (UserRoleOperateEntity userRoleOperateEntity : userRoleOperateEntities) {

                //节点
                if (userRoleOperateEntity.getType() == 0) {
                    UserRoleNodeTable userRoleNodeTable = new UserRoleNodeTable();
                    userRoleNodeTable.setNodeId(userRoleOperateEntity.getId());
                    userRoleNodeTable.setRoleId(roleId);
                    userRoleNodeTable.setAddIp(userRoleOperateListEntity.getModifyIp());
                    userRoleNodeTable.setAddTime(userRoleOperateListEntity.getModifyTime());
                    userRoleNodeTable.setAddUser(userRoleOperateListEntity.getModifyUser());
                    roleNodeTables.add(userRoleNodeTable);
                }
                //按钮
                else if (userRoleOperateEntity.getType() == 1) {
                    UserRoleDetailTable userRoleDetailTable = new UserRoleDetailTable();
                    userRoleDetailTable.setActionId(userRoleOperateEntity.getId());
                    userRoleDetailTable.setNodeId(userRoleOperateEntity.getPid());
                    userRoleDetailTable.setRoleId(roleId);
                    userRoleDetailTable.setAddIp(userRoleOperateListEntity.getModifyIp());
                    userRoleDetailTable.setAddTime(userRoleOperateListEntity.getModifyTime());
                    userRoleDetailTable.setAddUser(userRoleOperateListEntity.getModifyUser());
                    roleDetailTables.add(userRoleDetailTable);
                }
            }

            for (UserRoleDetailTable pojo : roleDetailTables) {
                boolean exist = false;
                for (UserRoleNodeTable nodePojo : roleNodeTables) {
                    if (pojo.getNodeId().equals(nodePojo.getId())) {
                        exist = true;
                        break;
                    }
                }
                if (exist) {
                    throw new RuntimeException(Constants.SYSTEM_ERROR);
                }
            }
        }

        /*
         * 修改原有的角色信息
         */
        userRoleNodeService.update(roleNodeTables, roleId);

        userRoleDetailService.update(roleDetailTables, roleId);

        /*
         * 更新内存中的角色信息
         */
        updateUserNode(roleId);
    }

    /**
     * 删除角色
     *
     * @param roleId
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleInfo(Long roleId) throws ServiceException {

        UserRoleTable userRoleTable = userRoleRepository.findOne(roleId);
        if (userRoleTable == null) {
            throw new ServiceException(Constants.INFO_NOT_FOUND);
        }

        /**
         * 检测当前角色下存在用户
         */
//        int count = sellerInfoDao.countByRoleIdAndShopId(roleId, shopId);
        int count = 0;
        if (count >= 1) {
            throw new SecurityException("角色下存在用户,不能删除!");
        }
        /*
         * 删除数据库数据信息
         */
        userRoleNodeService.deleteRoleNodeByRoleId(roleId);
        userRoleDetailService.deleteRoleDetailByRoleId(roleId);
        userRoleRepository.delete(userRoleTable);

        /**
         * 删除redis中数据
         */
        String requestId = GetRandom.getRandom(10);
        try {
            if (redisService.tryLock(RoleConstants.ROLE_LOCK + roleId, requestId, RoleConstants.ROLE_LOCK_ESPIRE_TIME)) {
                if (redisService.hasKey(RoleConstants.ROLE_USER_NODE + roleId)) {
                    redisService.remove(RoleConstants.ROLE_USER_NODE + roleId);
                }
                if (redisService.hasKey(RoleConstants.ROLE_USER_ACTION + roleId)) {
                    redisService.remove(RoleConstants.ROLE_USER_ACTION + roleId);
                }
            } else {
                throw new ServiceException("当前角色权限正在修改,请稍后重试!!!");
            }
        } finally {
            redisService.unlock(RoleConstants.ROLE_LOCK + roleId, requestId);
        }

    }

    /**
     * 获取单个角色信息
     *
     * @param roleId
     * @return
     * @throws ServiceException
     */
    @Override
    public UserRoleDto getRoleInfo(Long roleId) throws ServiceException {
        UserRoleTable userRoleTable = userRoleRepository.getFirstById(roleId);
        if (userRoleTable == null) {
            throw new ServiceException(Constants.INFO_NOT_FOUND);
        }

        return transform(userRoleTable);
    }

    @Autowired
    private TenantService tenantService;

    /**
     * 拉取角色列表
     *
     * @param userRoleSearchEntity
     * @return
     * @throws ServiceException
     */
    @Override
    public ResultWithPagerDto<UserRoleDto> getListInfo(UserRoleSearchEntity userRoleSearchEntity) throws ServiceException {

        Map<String, String> map = new LinkedHashMap<>(1);
        map.put("addTime", "desc");
        Pageable pageable = FormatPage.formatPageable(userRoleSearchEntity.getPage());
        Specification<UserRoleTable> specification = (root, query, cb) -> {

            List<Predicate> predicates = new ArrayList<>();

            if (ValidateUtil.vStringNull(userRoleSearchEntity.getName())) {
                predicates.add(cb.like(root.get("name").as(String.class), "%" + userRoleSearchEntity.getName() + "%"));
            }
            if (userRoleSearchEntity.getStartDate() != null) {
                predicates.add(cb.greaterThan(root.get("addTime").as(Date.class), userRoleSearchEntity.getStartDate()));
            }
            if (userRoleSearchEntity.getStartDate() != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("addTime").as(Date.class), userRoleSearchEntity.getEndDate()));
            }
            if (ValidateUtil.vStringNull(userRoleSearchEntity.getName())) {
                predicates.add(cb.like(root.get("name").as(String.class), "%" + userRoleSearchEntity.getName() + "%"));
            }
            if (userRoleSearchEntity.getMerchantId() != null) {
                predicates.add(cb.equal(root.get("merchantId"), userRoleSearchEntity.getMerchantId()));
            }
            //创建一个条件的集合，长度为上面满足条件的个数
            Predicate[] pre = new Predicate[predicates.size()];
            //这句大概意思就是将上面拼接好的条件返回去
            return query.where(predicates.toArray(pre)).getRestriction();
        };
        Page<UserRoleTable> pageResult = userRoleRepository.findAll(specification, pageable);
        PageDto pageDto = FormatPage.format(userRoleSearchEntity.getPage(), (int) pageResult.getTotalElements());

        if (pageResult.getTotalElements() <= 0) {
            return new ResultWithPagerDto(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, null, pageDto);
        }

        List<UserRoleDto> dtos = new ArrayList<>();
        List<TenantEntity> tenantEntities = tenantService.getAllMerchant();
        Map<Integer, TenantEntity> tenantMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(tenantEntities)){
            tenantMap = tenantEntities.stream().collect(Collectors.toMap(TenantEntity::getId, v -> v));
        }
        for (UserRoleTable userRoleTable : pageResult.getContent()) {
            UserRoleDto transform = transform(userRoleTable);
            if(tenantMap.containsKey(userRoleTable.getMerchantId())){
                transform.setMerchantName(tenantMap.get(userRoleTable.getMerchantId()).getMerchantName());
                transform.setMerchantId(userRoleTable.getMerchantId());
            }
            dtos.add(transform);
        }

        return new ResultWithPagerDto(Constants.SUCCESS_CODE, Constants.SEARCH_SUCCESS, dtos, pageDto);
    }

    /**
     * 获取所有店铺下角色信息列表
     *
     * @return
     * @throws ServiceException
     */
    @Override
    public List<UserAllRoleDto> getListInfo(Integer merchantId) throws ServiceException {
        List<UserRoleTable> roleTables = new ArrayList<>();
        if(merchantId != null){
            roleTables = userRoleRepository.findAllByMerchantId(merchantId);
        }else {
            roleTables = userRoleRepository.findAll();
        }
        List<UserAllRoleDto> allRoleDtos = new ArrayList<>();

        for (UserRoleTable sellerRoleTable : roleTables) {
            UserAllRoleDto shellerAllRoleDto = new UserAllRoleDto();
            BeanUtils.copyProperties(sellerRoleTable, shellerAllRoleDto);
            allRoleDtos.add(shellerAllRoleDto);
        }

        return allRoleDtos;
    }

    /**
     * 更新挂靠用户的数量
     *
     * @param entitys
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateNumber(List<UserRoleUpdateNumberEntity> entitys) throws ServiceException {

        if (entitys == null || entitys.size() <= 0) {
            return;
        }
        List<Long> ids = new ArrayList<>(entitys.size());

        Map<Long, UserRoleUpdateNumberEntity> map = new HashMap<>(entitys.size());

        entitys.forEach(value -> {
            ids.add(value.getId());
            map.put(value.getId(), value);
        });

        List<UserRoleTable> userRoleTables = userRoleRepository.findAllByIdIn(ids);
        if (userRoleTables == null || userRoleTables.size() <= 0) {
            return;
        }
        userRoleTables.forEach(userRoleTable -> {
            UserRoleUpdateNumberEntity userRoleUpdateNumberEntity = map.get(userRoleTable.getId());
            BeanUtils.copyProperties(userRoleUpdateNumberEntity, userRoleTable);
            int number = userRoleTable.getNumber() + userRoleUpdateNumberEntity.getChangeNumber();
            if (number < 0) {
                number = 0;
            }
            userRoleTable.setNumber(number);
        });

        userRoleRepository.save(userRoleTables);
    }

    /**
     * 更新挂靠用户的数量
     *
     * @param entity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateNumber(UserRoleUpdateNumberEntity entity) throws ServiceException {

        UserRoleTable userRoleTable = userRoleRepository.findFirstById(entity.getId());

        if (userRoleTable == null) {
            throw new ServiceException(ManagerConstant.ROLE_NOT_EXIST_ERROR);
        }

        BeanUtils.copyProperties(entity, userRoleTable);

        userRoleRepository.save(userRoleTable);
    }

    private UserRoleDto transform(UserRoleTable sellerRoleTable) {
        UserRoleDto shellerRoleDto = new UserRoleDto();
        BeanUtils.copyProperties(sellerRoleTable, shellerRoleDto);
        return shellerRoleDto;
    }

    /**
     * 修改权限
     *
     * @param roleId
     * @return
     * @throws ServiceException
     */
    private List<UserNodeDisplayDto> updateUserNode(Long roleId) throws ServiceException {

        /*
         * 获取节点信息
         */
        List<SysNodeView> sysNodeViews = userRoleNodeService.getSysNodesByRoleId(roleId);

        /*
         * 获取按钮信息
         */
        List<SysActionTable> sysActionTables = userActionRepository.getAllByOrderByCode();

//        if (sysActionTables == null || sysActionTables.size() == 0) {
//            throw new RuntimeException("权限信息有误，请联系管理员");
//        }
        /*
         * 获取详细信息
         */
        List<UserRoleDetailTable> roleDetailTables = new ArrayList<UserRoleDetailTable>();
        if (sysActionTables != null || sysActionTables.size() >= 0) {
            if (roleId != null && roleId != 0 && roleId != -1) {
                roleDetailTables = userRoleDetailService.getUserRoleDetailsByRoleId(roleId);
            } else {
                if (roleId != -1) {
                    for (SysActionTable sysActionTable : sysActionTables) {

                        UserRoleDetailTable userRoleDetailTable = new UserRoleDetailTable();
                        userRoleDetailTable.setActionId(sysActionTable.getId());
                        userRoleDetailTable.setRoleId(null);
                        userRoleDetailTable.setNodeId(sysActionTable.getNodeId());

                        roleDetailTables.add(userRoleDetailTable);
                    }
                }
            }
        }

        /*
         *  整合节点权限信息
         */
        List<UserNodeDisplayDto> userNodeDisplayEntities = new ArrayList<UserNodeDisplayDto>();
        if (sysNodeViews != null && sysNodeViews.size() > 0) {
            for (SysNodeView sysNodeTable : sysNodeViews) {
                if (sysNodeTable.getPid() == null || sysNodeTable.getPid() == 0) {
                    UserNodeDisplayDto userNodeDisplayEntity = getUserNodeDisplayDto(sysNodeTable);
                    recursion(sysNodeViews, sysActionTables, roleDetailTables, userNodeDisplayEntity);
                    userNodeDisplayEntities.add(userNodeDisplayEntity);
                }
            }
        }

        /*
         *  将结果存入redis中  redis记录简单加锁方式
         */
        String key;
        if (roleId == null || roleId == 0) {
            key = RoleConstants.ROLE_ADMIN;
        } else {
            key = roleId + "";
        }

        String requestId = System.currentTimeMillis() + "";
        try {
            if (redisService.tryLock(RoleConstants.ROLE_LOCK + key, requestId, RoleConstants.ROLE_LOCK_ESPIRE_TIME)) {
                /*
                 *  处理前端显示节点信息
                 */
                List<UserNodeDisplayDto> nodeList = new ArrayList<UserNodeDisplayDto>();
                nodeList.addAll(userNodeDisplayEntities);
                redisService.saveObject(RoleConstants.ROLE_USER_NODE + key, userNodeDisplayEntities);

                /*
                 * 处理后端角色判定信息
                 */
                List<String> actionList = new ArrayList<>();
                for (UserRoleDetailTable userRoleDetailPojo : roleDetailTables) {
                    for (SysActionTable sysActionPojo : sysActionTables) {
                        if (userRoleDetailPojo.getActionId().equals(sysActionPojo.getId())) {
                            actionList.add(sysActionPojo.getAction());
                        }
                    }
                }
                redisService.saveObject(RoleConstants.ROLE_USER_ACTION + key, actionList);
            } else {
                throw new ServiceException("当前角色权限正在修改,请稍后重试!!!");
            }
        } finally {
            redisService.unlock(RoleConstants.ROLE_LOCK + key, requestId);
        }
        return userNodeDisplayEntities;
    }

    /**
     * 递归节点信息，获取前台展示的节点数据
     *
     * @param sysNodeViews
     * @param sysActionTables
     * @param userRoleDetailTables
     * @param userNodeDisplayDto
     */
    private void recursion(List<SysNodeView> sysNodeViews, List<SysActionTable> sysActionTables,
                           List<UserRoleDetailTable> userRoleDetailTables, UserNodeDisplayDto userNodeDisplayDto) {
        for (SysNodeView sysNodePojo : sysNodeViews) {
            if (userNodeDisplayDto.getId().equals(sysNodePojo.getPid())) {
                UserNodeDisplayDto child = getUserNodeDisplayDto(sysNodePojo);

                Map<String, UserActionDisplayDto> userActionDisplayDtos = getUserActionDisplayDtos(sysActionTables, userRoleDetailTables, child.getId());
                child.setBtns(userActionDisplayDtos);

                userNodeDisplayDto.getChildren().add(child);
                recursion(sysNodeViews, sysActionTables, userRoleDetailTables, child);
            } else {
                Map<String, UserActionDisplayDto> userActionDisplayDtos = getUserActionDisplayDtos(sysActionTables, userRoleDetailTables, userNodeDisplayDto.getId());
                userNodeDisplayDto.setBtns(userActionDisplayDtos);
            }
        }
    }

    private Map<String, UserActionDisplayDto> getUserActionDisplayDtos(List<SysActionTable> sysActionTables, List<UserRoleDetailTable> userRoleDetailTables, Long nodeId) {

        if (sysActionTables == null && sysActionTables.size() <= 0) {
            return new HashMap<>(0);
        }
        Map<String, UserActionDisplayDto> userActionDisplayDtos = new HashMap<>(sysActionTables.size());
        List<SysActionTable> removeSysActionTables = new ArrayList<>(sysActionTables.size());
        int size = sysActionTables.size();

        for (int i = 0; i < size; i++) {
            SysActionTable sysActionPojo = sysActionTables.get(i);
            if (sysActionPojo.getNodeId().equals(nodeId)) {
                UserActionDisplayDto userActionDisplayDto = getUserActionDisplayDto(sysActionPojo, userRoleDetailTables, nodeId);
                userActionDisplayDtos.put(userActionDisplayDto.getCode(), userActionDisplayDto);
                removeSysActionTables.add(sysActionPojo);
            }
        }
        if (removeSysActionTables.size() > 0) {
            userRoleDetailTables.removeAll(removeSysActionTables);
        }
        return userActionDisplayDtos;
    }

    private UserActionDisplayDto getUserActionDisplayDto(SysActionTable sysActionTable, List<UserRoleDetailTable> userRoleDetailTables, Long nodeId) {
        if (sysActionTable.getNodeId() != null && sysActionTable.getNodeId().equals(nodeId)) {
            UserActionDisplayDto userActionDisplayDto = new UserActionDisplayDto();
            userActionDisplayDto.setName(sysActionTable.getName());
            userActionDisplayDto.setCode(sysActionTable.getCode());
            userActionDisplayDto.setId(sysActionTable.getId());
            userActionDisplayDto.setPid(sysActionTable.getNodeId());
            userActionDisplayDto.setShow(false);
            userActionDisplayDto.setTId(userActionDisplayDto.getId() + "-" + userActionDisplayDto.getType());
            if (userRoleDetailTables != null && userRoleDetailTables.size() != 0) {
                Iterator<UserRoleDetailTable> userRoleDetailPojoIterator = userRoleDetailTables.iterator();
                while (userRoleDetailPojoIterator.hasNext()) {
                    UserRoleDetailTable userRoleDetailPojo = userRoleDetailPojoIterator.next();
                    if (userRoleDetailPojo.getNodeId().equals(nodeId)
                            && userRoleDetailPojo.getActionId().equals(sysActionTable.getId())) {
                        userActionDisplayDto.setShow(true);
                    }
                }
            }
            return userActionDisplayDto;
        }
        return null;
    }

    private UserNodeDisplayDto getUserNodeDisplayDto(SysNodeView sysNodeTable) {
        UserNodeDisplayDto userNodeDisplayEntity = new UserNodeDisplayDto();
        userNodeDisplayEntity.setName(sysNodeTable.getName());
        userNodeDisplayEntity.setCode(sysNodeTable.getCode());
        userNodeDisplayEntity.setIcon(sysNodeTable.getIcon());
        userNodeDisplayEntity.setLink(sysNodeTable.getLink());
        userNodeDisplayEntity.setId(sysNodeTable.getId());
        userNodeDisplayEntity.setShow(sysNodeTable.getShow());
        userNodeDisplayEntity.setPid(sysNodeTable.getPid());
        userNodeDisplayEntity.setSubIndex(sysNodeTable.getSubIndex());
        userNodeDisplayEntity.setTId(sysNodeTable.getId() + "-" + userNodeDisplayEntity.getType());
        return userNodeDisplayEntity;
    }

    @Override
    public String getRoleCodeById(Long id) throws ServiceException {

        UserRoleTable userRoleTable = userRoleRepository.getOne(id);
        if (userRoleTable == null) {
            throw new ServiceException("info_not_found");
        }
        return userRoleTable.getCode();
    }

    @Override
    public Long getIdByRoleCode(String code) throws Exception {


        UserRoleTable userRoleTable = userRoleRepository.getFirstByCode(code);
        if (userRoleTable == null){
            return null;
        }else{
            return userRoleTable.getId();
        }
    }

    @Override
    public UserRoleTable findRoleInfo(Long roleId) {
        UserRoleTable userRoleTable = userRoleRepository.getOne(roleId);
        return userRoleTable;
    }
}
