package com.lightinit.hsdataplatformresdir.controller;

import com.lightinit.hsdataplatformresdir.json.pojo.ErrorEntity;
import com.google.code.kaptcha.Constants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import com.lightinit.hsdataplatformresdir.json.pojo.LoginResult;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Mr.Yao on 2017/4/7.
 */
@Controller
@RequestMapping("/passport")
public class LoginController {

    @RequestMapping(value = {"login.htm", "login"},method = RequestMethod.GET)
    public String printMain(ModelMap model) {
        return "index";
    }
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "login.action")
    public  LoginResult printLoginAction(ModelMap model,HttpSession session, @RequestParam String username,@RequestParam String password,@RequestParam String captcha){
        LoginResult result = new LoginResult();
       String capText=session.getAttribute(Constants.KAPTCHA_SESSION_KEY)!=null?session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString():"";
        if(StringUtils.isEmpty(capText) || StringUtils.isEmpty(captcha)){
            result.setStatus(0003);
        }else if (capText.equalsIgnoreCase(captcha)==false){
            result.setStatus(2010);
        }else {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject currentUser = SecurityUtils.getSubject();
            //token.setRememberMe(true);
            try {
                //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
                currentUser.login(token);
                if (currentUser.isAuthenticated()) {
                    session.setAttribute("userinfo", username);
                    result.setStatus(2001);
                } else {
                    token.clear();
                }
            } catch (UnknownAccountException uae) {
                result.setStatus(2003);
                token.clear();
            } catch (IncorrectCredentialsException ice) {
                result.setStatus(2004);
                token.clear();
            } catch (LockedAccountException lae) {
                result.setStatus(2005);
                token.clear();
            } catch (ExcessiveAttemptsException eae) {
                result.setStatus(2006);
                token.clear();
            } catch (AuthenticationException ae) {
                //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
                result.setStatus(2007);
            }
        }
        result.setMessage(ErrorEntity.getMsg(result.getStatus()));
        return result;
    }
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "logout.action")
    public  LoginResult printLogoutAction(ModelMap model,HttpSession session){
        LoginResult result = new LoginResult();
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.logout();
            result.setStatus(2008);
        } catch (Exception e) {
            result.setStatus(0003);
        }
        result.setMessage(ErrorEntity.getMsg(result.getStatus()));
        return result;
    }
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET,value = "auth.action")
    public ModelAndView printAuthAction(ModelMap model, HttpServletRequest request, HttpServletResponse response,@CookieValue(defaultValue = "") String username){
        try {
           if(StringUtils.isEmpty(username)){
               response.setStatus(401);
           }else{
               response.setStatus(200);
           }
        } catch (Exception e) {
            response.setStatus(401);
        }
        return null;
    }
}
