package com.red.circle.console.app.command.admin.query;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.red.circle.console.app.convertor.RoleAppConvertor;
import com.red.circle.console.app.dto.clienobject.admin.RoleCO;
import com.red.circle.console.app.dto.cmd.admin.PageRoleQryCmd;
import com.red.circle.console.infra.database.rds.entity.admin.Role;
import com.red.circle.console.infra.database.rds.service.admin.RoleMenuService;
import com.red.circle.console.infra.database.rds.service.admin.RoleService;
import com.red.circle.framework.dto.PageResult;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

/**
 * 角色分页列表.
 * @author pengliang on 2023/5/12
 */
@Component
@RequiredArgsConstructor
public class RolePageQryExe {

    private final RoleService roleService;
    private final RoleMenuService roleMenuService;
    private final RoleAppConvertor roleAppConvertor;

    private static final Logger log = LoggerFactory.getLogger(RolePageQryExe.class);

    public PageResult<RoleCO> execute(PageRoleQryCmd cmd) {
        log.info("RolePageQryExe execute{}", JSON.toJSONString(cmd));
        PageResult<Role> rolePageResult = roleService.query()
                .like(StringUtils.isNotEmpty(cmd.getRoleName()), Role::getRoleName, cmd.getRoleName())
                .orderByDesc(Role::getCreateTime)
                .page(cmd.getPageQuery());

        Map<Integer, List<Integer>> roleMenus = roleMenuService.mapRoleMenuIds(
                rolePageResult.getRecords().stream().map(Role::getId).collect(
                        Collectors.toSet()));

        return rolePageResult.convert(role -> {
            RoleCO co = roleAppConvertor.toRoleCO(role);
            co.setMenuIds(roleMenus.get(role.getId()));
            return co;
        });
    }

}
