package com.xunmei.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunmei.common.core.utils.StringUtils;
import com.xunmei.common.core.web.domain.AjaxResult;
import com.xunmei.system.domain.SysMenu;
import com.xunmei.system.mapper.MenuMapper;
import com.xunmei.system.service.IMenuService;
import org.springframework.stereotype.Service;

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

import static com.xunmei.common.core.web.domain.AjaxResult.success;

/**
 * @author luojun
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, SysMenu> implements IMenuService {

    @Override
    public AjaxResult findListByPage(Page<SysMenu> page, SysMenu sysMenu) {
        QueryWrapper<SysMenu> where = new QueryWrapper<>(sysMenu);
        return success(baseMapper.selectPage(page, where));
    }

    @Override
    public AjaxResult add(SysMenu sysMenu) {
        return success(baseMapper.insert(sysMenu));
    }

    @Override
    public AjaxResult delete(Long id) {
        return success(baseMapper.deleteById(id));
    }

    @Override
    public AjaxResult updateData(SysMenu sysMenu) {
        return success(baseMapper.updateById(sysMenu));
    }

    @Override
    public AjaxResult findById(Long id) {
        return success(baseMapper.selectById(id));
    }

    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = baseMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = baseMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }
}
