package com.simuwang.manage.service;

import com.simuwang.base.common.util.TreeUtil;
import com.simuwang.base.components.UserAuthService;
import com.simuwang.base.pojo.dos.sys.SysMenuDO;
import com.simuwang.base.pojo.dos.sys.SysRoleDO;
import com.simuwang.base.pojo.dos.sys.SysUserDO;
import com.simuwang.manage.dto.MenuTreeDTO;
import com.simuwang.manage.dto.UserInfoVO;
import com.simuwang.manage.dto.UserRoleDTO;
import com.simuwang.shiro.core.ShiroUser;
import com.simuwang.shiro.utils.UserUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author wangzaijun
 * @date 2024/9/12 20:28
 * @description 系统管理服务
 */
@Service
public class LoginService {
    private final UserAuthService userAuthService;

    public LoginService(UserAuthService userAuthService) {
        this.userAuthService = userAuthService;
    }

    /**
     * 获取当前用户的权限角色信息
     *
     * @return /
     */
    public UserInfoVO getUserInfo() {
        ShiroUser shiroUser = UserUtils.getLoginUser();
        Integer userId = shiroUser.getUserId();
        String username = shiroUser.getUsername();
        SysUserDO userInfo = this.userAuthService.getUserInfoByUsername(username);
        // 用户角色信息转换
        List<SysRoleDO> roleList = this.userAuthService.listUserRoleByUserId(userId);
        List<UserRoleDTO> roles = roleList.stream()
                .map(e -> new UserRoleDTO(e.getRoleId(), e.getRoleName(), e.getRoleKey()))
                .distinct().collect(Collectors.toList());
        // 用户权限处理
        List<SysMenuDO> menuList = this.userAuthService.listUserMenuByUserId(userId);
        List<MenuTreeDTO> tempList = menuList.stream().map(MenuTreeDTO::new).collect(Collectors.toList());
        // 菜单列表转树结构
        List<MenuTreeDTO> trees = TreeUtil.list2Tree(tempList, MenuTreeDTO::getId, MenuTreeDTO::getPid,
                MenuTreeDTO::getChildren, MenuTreeDTO::setChildren, 0, MenuTreeDTO::getSort);
        MenuTreeDTO root = new MenuTreeDTO(0, "全部菜单", trees);
        // 返回的数据结构构建
        UserInfoVO vo = new UserInfoVO(userId, username, roles, root);
        vo.setEmail(userInfo.getEmail());
        vo.setPhonenumber(userInfo.getPhonenumber());
        return vo;
    }
}
