package cn.reghao.bnt.web.admin.controller;

import cn.reghao.bnt.web.admin.model.dto.RsaPubkey;
import cn.reghao.bnt.web.admin.service.CodeService;
import cn.reghao.bnt.web.admin.service.PubkeyService;
import cn.reghao.jutil.jdk.web.result.WebResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author reghao
 * @date 2023-04-17 10:06:05
 */
@Tag(name = "后台登入页")
@Controller
public class LoginController {
    private final CodeService codeService;
    private final PubkeyService pubkeyService;

    public LoginController(CodeService codeService, PubkeyService pubkeyService) {
        this.codeService = codeService;
        this.pubkeyService = pubkeyService;
    }

    @Operation(summary = "登入页面", description = "N")
    @GetMapping(value = "/bg/login")
    public String loginPage(@RequestParam(value = "loginType", required = false) Integer loginType) {
        String view = "/classic/auth/login2";
        return view;
    }

    @Operation(summary = "获取公钥", description = "N")
    @GetMapping(value = "/api/auth/code/pubkey", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String getPubkey(@RequestParam("channel") int channel) throws NoSuchAlgorithmException {
        RsaPubkey rsaPubkey = pubkeyService.getPubkey();
        return WebResult.success(rsaPubkey);
    }

    @Operation(summary = "获取图形验证码", description = "N")
    @GetMapping(value = "/api/auth/code/captcha", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String getCaptcha() throws IOException {
        InputStream in = codeService.generateCaptcha();
        byte[] base64Bytes = Base64.getEncoder().encode(in.readAllBytes());
        String base64Str = new String(base64Bytes, StandardCharsets.UTF_8);
        String imageStr = String.format("data:image/jpeg;base64,%s", base64Str);
        return WebResult.success(imageStr);
    }

    /*@Operation(summary = "单点登出", description = "N")
    @GetMapping("/bg/sso/signout")
    public void ssoLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        new SecurityContextLogoutHandler().logout(request, null, null);
        String referer = request.getHeader("referer");
        response.sendRedirect(referer);
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        response.setDateHeader("Expires", 0); // Proxies.
    }*/
}
