package com.lightinit.hsdataplatform.controller.admin;

import com.google.code.kaptcha.Constants;
import com.lightinit.hsdataplatform.common.ConfigUtils;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.TokenUntils;
import com.lightinit.hsdataplatform.json.pojo.ErrorEntity;
import com.lightinit.hsdataplatform.json.pojo.LoginResult;
import com.lightinit.hsdataplatform.model.admin.LoginUser;
import com.lightinit.hsdataplatform.service.admin.IAccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 WangYao on 2018/5/21.
 */
@Controller("adminAccountController")
@RequestMapping("/admin/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @RequestMapping(value = {"login.htm", "login"},method = RequestMethod.GET)
    public String printMain(ModelMap modelMap) {
        return "admin/account/login";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "login.action")
    public LoginResult printLoginAction(ModelMap model,HttpSession session, @RequestParam String username,@RequestParam String password){
        LoginResult result = new LoginResult();
        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);
                session.setAttribute(LoginUser.SESSION_KEY_LOGIN_USER, accountService.getLoginUserByUsername(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 ModelAndView logout(ModelMap model,HttpSession session){
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.logout();
        } catch (Exception e) {
        }
        String loyout = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CAS).getString(SysContants.CasKey.REDIRECTURL) ;

        return new ModelAndView("redirect:"+loyout);
    }

    @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;
    }
}
