package com.trade.admin.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.trade.admin.system.dto.UserInfoDTO;
import com.trade.admin.system.service.ISysLoginService;
import com.trade.common.constant.Constants;
import com.trade.admin.system.domain.entity.SysMenu;
import com.trade.admin.system.domain.entity.SysUser;
import com.trade.admin.system.domain.model.LoginBody;
import com.trade.admin.system.domain.vo.RouterVo;
import com.trade.admin.system.security.utils.SecurityUtils;
import com.trade.admin.system.service.ISysMenuService;
import com.trade.admin.system.service.ISysPermissionService;
import com.trade.common.core.domain.ResponseResult;
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;

/**
 * 登录验证
 *
 * @author wl
 */
@RestController
public class SysLoginController {

    @Autowired
    private ISysLoginService loginService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private ISysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public ResponseResult<Map> login(@RequestBody LoginBody loginBody) {
        Map<String, String> tokenMap = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        tokenMap.put(Constants.TOKEN, token);
        return ResponseResult.success(tokenMap);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public ResponseResult<UserInfoDTO> getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);

        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUser(user);
        userInfoDTO.setRoles(roles);
        userInfoDTO.setPermissions(permissions);
        return ResponseResult.success(userInfoDTO);
    }

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