package com.tuoheng.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.jaas.SecurityContextLoginModule;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chenjiandong
 * @description: TODO
 * @date 2022/10/9 14:57
 */
@Slf4j
@Controller
public class Oauth2Controller {

    @GetMapping("toLogin")
    public String login(@RequestParam(value = "error", required = false) String error,
                        @RequestParam(value = "validerror", required = false) String validerror,
                        @RequestParam(value = "expirecode", required = false) String expirecode,
                        @RequestParam(value = "logout", required = false) String logout, Model model) {
        if (error != null) {
            model.addAttribute("msg", "用户名或密码错误！");
        }
        if(validerror!=null){
            model.addAttribute("msg", "验证码错误！");
        }
        if(validerror!=expirecode){
            model.addAttribute("msg", "验证码已过期！");
        }
        if (logout != null) {
            model.addAttribute("msg", "成功退出！");
        }
        return "login";

    }

    @GetMapping("/toLogout")
    public void exit(HttpServletRequest request, HttpServletResponse response) {
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
            System.out.println(request.getHeader("referer"));
            response.sendRedirect(request.getHeader("referer"));
            //response.sendRedirect("http://192.168.13.140:3000/home");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}