/*
 * Copyright (c) 2019, PANNK and/or its affiliates. All rights reserved.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */
package com.pannk.mms.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pannk.mms.common.base.Constant;
import com.pannk.mms.common.utils.ListUtil;
import com.pannk.mms.common.utils.RedisUtil;
import com.pannk.mms.modules.sys.dao.SysMenuMapper;
import com.pannk.mms.modules.sys.entity.SysMenuEntity;
import com.pannk.mms.modules.sys.service.SysMenuService;
import com.pannk.mms.modules.sys.vo.SysMenuInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系统菜单服务
 *
 * @author：wolf
 * @date：2020/11/2 23:36
 **/
@Slf4j
@Service("sysMenuService")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenuEntity> implements SysMenuService {


    @Autowired
    private RedisUtil redisUtil;

    @Override
    public SysMenuInfo getUserMenuList(Long userId) {
        List<SysMenuEntity> userMenuList = userId == Constant.SUPER_ADMIN ? getUserMenu(null) : getUserMenu(userId);
        List<SysMenuEntity> menuList = getMenuList(userMenuList);
        Set<String> permissions = userId == Constant.SUPER_ADMIN ? baseMapper.queryUserPerms(null) : baseMapper.queryUserPerms(userId);
        redisUtil.set(Constant.PERMS_CAHCE + userId, permissions);
        return new SysMenuInfo(menuList, permissions);
    }


    private List<SysMenuEntity> getUserMenu(Long userId) {
        return baseMapper.queryMenuList(userId);
    }

    private List<SysMenuEntity> getMenuList(List<SysMenuEntity> all) {
        if (!ListUtil.isEmpty(all)) {
            return queryListByParentId(0L, all);
        }
        return null;
    }

    private List<SysMenuEntity> queryListByParentId(Long parentId, List<SysMenuEntity> menuList) {
        List<SysMenuEntity> result = new ArrayList<>();
        for (SysMenuEntity sysMenuEntity : menuList) {
            if (sysMenuEntity.getParentId() == parentId) {
                List<SysMenuEntity> subMenuList = queryListByParentId(sysMenuEntity.getId(), menuList);
                if (!ListUtil.isEmpty(subMenuList)) {
                    sysMenuEntity.setList(subMenuList);
                }
                result.add(sysMenuEntity);
            }
        }
        return result;
    }
}
