package com.simuwang.manage.api;

import cn.hutool.core.map.MapUtil;
import com.simuwang.base.pojo.dto.sys.UserUpdatePwdCmd;
import com.simuwang.logging.SystemLog;
import com.simuwang.manage.dto.LoginUser;
import com.simuwang.manage.dto.UserInfoVO;
import com.simuwang.manage.service.LoginService;
import com.simuwang.shiro.core.jwt.JwtContext;
import com.smppw.common.pojo.ResultVo;
import com.smppw.common.pojo.enums.status.ResultCode;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 登录相关接口
 */
@RestController
@RequestMapping("/v1")
public class LoginController {
    private final LoginService loginService;

    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    /**
     * 获取rsk公钥
     *
     * @return /
     */
//    @SystemLog(value = "获取公钥", type = SystemLog.Type.QUERY)
    @GetMapping("rsa-key")
    public Map<String, Object> getRsaKey() {
        return MapUtil.<String, Object>builder("rsaKey", this.loginService.getRsaPublicKey()).build();
    }

    /**
     * 用户登录
     *
     * @param loginUser 登录用户账号和密码
     *                  //     * @param response  响应体对象
     * @return /
     */
    @SystemLog(value = "登录", type = SystemLog.Type.LOGIN)
    @PostMapping("login")
    public ResultVo<String> login(@RequestBody LoginUser loginUser, HttpServletResponse response) {
        String token = this.loginService.login(loginUser);
        response.setHeader(JwtContext.HEADER, token);
        response.setHeader("Access-control-Expost-Headers", JwtContext.HEADER);
        return ResultVo.ok(ResultCode.SUCCESS.getCode(), "登录成功", token);
    }

    /**
     * 退出登录接口，登录用户才能访问
     */
    @SystemLog(value = "登出", type = SystemLog.Type.LOGOUT)
    @PostMapping("/logout")
    public ResultVo<Boolean> logout() {
        return ResultVo.ok(ResultCode.SUCCESS.getCode(), "退出成功", this.loginService.logout());
    }

    /**
     * 获取当前用户的角色权限信息（只在登录时获取一次）
     *
     * @return 当前登录用户的角色权限信息
     */
//    @SystemLog(value = "获取当前登录用户信息")
    @GetMapping("/user-info")
    public UserInfoVO getUserInfo() {
        return this.loginService.getUserInfo();
    }

    /**
     * 修改密码
     *
     * @param command 修改密码对象
     */
    @SystemLog(value = "修改密码", type = SystemLog.Type.UPDATE)
    @PostMapping("update-pwd")
    public boolean updatePwd(@Valid @RequestBody UserUpdatePwdCmd command) {
        this.loginService.updatePwd(command);
        return true;
    }
}
