package com.qiaoba.auth.controller;

import com.qiaoba.api.auth.utils.SecurityUtil;
import com.qiaoba.api.system.entity.dto.LoginDto;
import com.qiaoba.api.system.entity.vo.SysMenuVo;
import com.qiaoba.api.system.service.SysMenuApiService;
import com.qiaoba.auth.service.SysLoginService;
import com.qiaoba.common.base.result.AjaxResult;
import lombok.RequiredArgsConstructor;
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 java.util.List;
import java.util.Set;

/**
 * 登录 Web层
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/5 9:43
 */
@RestController
@RequiredArgsConstructor
public class SysLoginController {

    private final SysMenuApiService sysMenuApiService;
    private final SysLoginService sysLoginService;

    @GetMapping("/captchaImage")
    public AjaxResult getCaptchaImage() {
        AjaxResult result = AjaxResult.success();
        result.putAll(sysLoginService.getCaptchaImage());
        return result;
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDto dto) {
        String token = sysLoginService.login(dto);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("token", token);
        return ajax;
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        List<String> roles = SecurityUtil.getLoginUser().getRoleKeys();
        Set<String> permissions = SecurityUtil.getLoginUser().getPermissions();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("permissions", permissions);
        ajax.put("roles", roles);
        ajax.put("user", SecurityUtil.getLoginUser());
        return ajax;
    }

    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        List<SysMenuVo> sysMenuVos = sysMenuApiService.selectByUserId(SecurityUtil.getLoginUserId());
        return AjaxResult.success(sysMenuApiService.menusToRouters(sysMenuVos));
    }

}
