package com.zbf.web.controller.system;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbf.common.constant.Constants;
import com.zbf.common.core.domain.AjaxResult;
import com.zbf.common.core.domain.TreeSelect;
import com.zbf.common.core.domain.entity.SysMenu;
import com.zbf.common.core.domain.entity.SysUser;
import com.zbf.common.core.domain.model.LoginBody;
import com.zbf.common.utils.RsaUtils;
import com.zbf.common.utils.SecurityUtils;
import com.zbf.framework.web.service.SysLoginService;
import com.zbf.framework.web.service.SysPermissionService;
import com.zbf.system.domain.TBaseStorage;
import com.zbf.system.domain.TUserFavorites;
import com.zbf.system.domain.vo.MetaVo;
import com.zbf.system.domain.vo.RouterVo;
import com.zbf.system.mapper.TUserFavoritesMapper;
import com.zbf.system.service.ISysDeptService;
import com.zbf.system.service.ISysMenuService;
import com.zbf.system.service.ITBaseStorageService;

import cn.hutool.json.JSONUtil;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    private final SysLoginService loginService;

    private final ISysMenuService menuService;

    private final SysPermissionService permissionService;

    @Autowired
    private ITBaseStorageService baseStorageService;

    private ISysDeptService deptService;
    private TUserFavoritesMapper favoritesMapper;

    public SysLoginController(ISysDeptService deptService, SysLoginService loginService, ISysMenuService menuService, SysPermissionService permissionService, TUserFavoritesMapper favoritesMapper) {
        this.deptService = deptService;
        this.loginService = loginService;
        this.menuService = menuService;
        this.permissionService = permissionService;
        this.favoritesMapper = favoritesMapper;
    }
    /**
     * 获取公钥 前端用来密码加密
     *
     * @return
     */
        @GetMapping("/publicKey")
    public RsaUtils.RsaKeyPair publicKey() {
        return RsaUtils.rsaKeyPair();
    }
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<TreeSelect> deptList = deptService.selectDeptTreeList(deptService.selectDeptById(user.getDeptId()));
        // 根据用户ID查询出此用户所有收藏的状态为有效的路由 只查询10条
        LambdaQueryWrapper<TUserFavorites> query = new LambdaQueryWrapper<TUserFavorites>();
        query.eq(TUserFavorites::getUserId, user.getUserId());
        query.eq(TUserFavorites::getStatus, "0");
        query.orderByDesc(TUserFavorites::getUpdateTime);
        List<TUserFavorites> favorites = favoritesMapper.selectList(query);
        List<RouterVo> routers = favorites.stream().map(favorite -> {
            MetaVo metaVo = JSONUtil.toBean(favorite.getMeta(), MetaVo.class);
            RouterVo routerVo = new RouterVo();
            routerVo.setId(favorite.getId());
            routerVo.setMeta(metaVo);
            routerVo.setPath(favorite.getFullPath());
            routerVo.setName(favorite.getTitle());
            return routerVo;
        }).collect(Collectors.toList());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);

        // 获取用户所属仓库列表
        TBaseStorage baseStorage = new TBaseStorage();
        baseStorage.setDeptId(user.getDeptId());
        List<TBaseStorage> tStorages = baseStorageService.selectTBaseStorageList(baseStorage);

        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("deptList", deptList);
        ajax.put("storageList", tStorages.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
        int toIdx = routers.size() > 10 ? 10 : routers.size();
        ajax.put("favoriteRouter", routers.subList(0, toIdx)); // 当前用户收藏的路由信息
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
