package com.lightinit.hsdataportal.controller.share;

import com.lightinit.hsdataportal.common.ConfigUtils;
import com.lightinit.hsdataportal.common.SysContants;
import com.lightinit.hsdataportal.controller.BaseController;
import com.lightinit.hsdataportal.model.LoginUser;
import com.lightinit.hsdataportal.model.ResultState;
import com.lightinit.hsdataportal.model.ResultStateCode;
import com.lightinit.hsdataportal.model.ShareRegisterModel;
import com.lightinit.hsdataportal.service.share.IAccountService;
import com.lightinit.hsdataportal.spring.UsernamePasswordUserTypeToken;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

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

/**
 * Created by WangYao on 2018/6/7.
 */
@Controller("shareAccountController")
@RequestMapping(value = "/share/account")
public class AccountController extends BaseController {

    @Autowired
    private IAccountService accountService;

    @RequestMapping(value = "login.htm")
    public String login(ModelMap model, HttpServletRequest request) {
        if (SecurityUtils.getSubject().isAuthenticated()){
            return "/" ;
        }else {
            String casservice = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CAS).getString(SysContants.CasKey.CASSERVICE) ;
            return "redirect:"+casservice;
        }
    }

    @RequestMapping(value = "login.action")
    public String doLogin(Model model, HttpSession session, HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
        ResultState resultState = new ResultState();
        model.addAttribute("resultState", resultState);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("用户名和密码不能为空");
            return "share/account/login";
        }
        UsernamePasswordUserTypeToken token = new UsernamePasswordUserTypeToken(username, password, "admin");
        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));
            } else {
                token.clear();
            }
        } catch (UnknownAccountException uae) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("用户名不存在");
            token.clear();
        } catch (IncorrectCredentialsException ice) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("用户名或密码错误");
            token.clear();
        } catch (LockedAccountException lae) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("用户被锁定");
            token.clear();
        } catch (ExcessiveAttemptsException eae) {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("尝试次数过多");
            token.clear();
        } catch (AuthenticationException ae) {
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("用户名或密码错误");
        }

        if (resultState.getStateCode() == ResultStateCode.SUCCESS){
            SavedRequest savedRequest = WebUtils.getSavedRequest(request);
            if (savedRequest != null){
                String returnUrl = WebUtils.getSavedRequest(request).getRequestUrl();
                if (StringUtils.isNotEmpty(returnUrl)){
                    return InternalResourceViewResolver.REDIRECT_URL_PREFIX + returnUrl;
                }
            }
            return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/";
        }
        return "share/account/login";
    }

    @RequestMapping(value = "logout.action")
    public String logout(ModelMap model, HttpSession session){
        String redirecturl = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CAS).getString(SysContants.CasKey.REDIRECTURL);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.logout();
            session.invalidate();
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
        return InternalResourceViewResolver.REDIRECT_URL_PREFIX + redirecturl;
    }

}
