package com.ningdatech.pmapi.sys.manage;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.pmapi.sys.model.entity.Menu;
import com.ningdatech.pmapi.sys.model.entity.Role;
import com.ningdatech.pmapi.sys.model.entity.RoleMenu;
import com.ningdatech.pmapi.sys.model.req.RolePageReq;
import com.ningdatech.pmapi.sys.model.vo.MenuRoleVO;
import com.ningdatech.pmapi.sys.model.vo.RoleVO;
import com.ningdatech.pmapi.sys.service.IRoleMenuService;
import com.ningdatech.pmapi.sys.service.IMenuService;
import com.ningdatech.pmapi.sys.service.IRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色管理
 * </p>
 *
 * @author WendyYang
 * @since 12:01 2023/1/28
 */
@Component
@RequiredArgsConstructor
public class RoleManage {

    private final IRoleService IRoleService;
    private final IMenuService IMenuService;

    private final IRoleMenuService roleMenuService;

    public PageVo<RoleVO> queryList(RolePageReq rolePageReq) {
        Page<Role> page = rolePageReq.page();
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery(Role.class);
        searchList(page, wrapper, rolePageReq);
        List<RoleVO> data = CollUtils.convert(page.getRecords(), w -> BeanUtil.copyProperties(w, RoleVO.class));
        return PageVo.of(data, page.getTotal());
    }

    private void searchList(Page<Role> page, LambdaQueryWrapper<Role> wrapper, RolePageReq rolePageReq) {
        wrapper.like(StringUtils.isNotBlank(rolePageReq.getName()), Role::getName, rolePageReq.getName())
                .orderByDesc(Role::getUpdateOn);
        IRoleService.page(page, wrapper);
    }


    public void buildMenu(RoleVO query) {
        //改成直接返回有权限的
        List<Menu> list = IMenuService.list(Wrappers.lambdaQuery(Menu.class).orderByAsc(Menu::getSort));
        List<RoleMenu> roleMenus = roleMenuService.list(Wrappers.lambdaQuery(RoleMenu.class)
                .eq(RoleMenu::getRoleId, query.getId()));
        List<MenuRoleVO> menus = list.stream().map(menu -> {
            for (RoleMenu roleMenu : roleMenus) {
                if (roleMenu.getMenuId().equals(menu.getId())) {
                    return BeanUtil.copyProperties(menu, MenuRoleVO.class);
                }
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        query.setMenu(menus);
    }

}
