package cn.com.qmth.examcloud.tool.controller;

import cn.com.qmth.examcloud.tool.cache.LoginSessionManager;
import cn.com.qmth.examcloud.tool.config.Constants;
import cn.com.qmth.examcloud.tool.service.CommonService;
import cn.com.qmth.examcloud.tool.vo.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private CommonService commonService;

    @GetMapping(value = "/login")
    public String login() {
        if (currentLoginUser() != null) {
            return "redirect:/admin/workspace";
        }
        return "login";
    }

    @PostMapping(value = "/login")
    public void doLogin(@RequestParam String serverUrl, @RequestParam String loginName, @RequestParam String password,
                        @RequestParam(required = false) String smsCode) {
        User user = commonService.login(serverUrl, loginName, password, smsCode);
        currentSession().setAttribute(Constants.LOGIN_USER, user);
    }

    @GetMapping(value = "/logout")
    public String logout() {
        User user = currentLoginUser();
        if (user != null) {
            LoginSessionManager.removeLoginSession(user.getToken());
            currentSession().removeAttribute(Constants.LOGIN_USER);
        }
        return "redirect:/login";
    }

}
