package org.springblade.common.auth.permission;

import com.alibaba.fastjson.JSONObject;
import org.springblade.common.auth.UserContext;
import org.springblade.common.auth.UserContextUtil;
import org.springblade.common.auth.config.SpringCasAutoconfig;
import java.io.IOException;
import java.security.Principal;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import static org.springblade.common.auth.permission.PermissionDefinition.MAX_INACTIVE_SECONDS_ONE_DAY;

@Component
@Slf4j
@ConditionalOnProperty(name = "cas.support.flag", havingValue = "true", matchIfMissing = false)
public class CasSecurityInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private SpringCasAutoconfig autoconfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws IOException, ParseException {
        HttpSession session = request.getSession();
        //获取cas给我们传递回来的对象，这个东西放到了session中
        //session的 key是 _const_cas_assertion_
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        if (assertion == null) {
            log.info("URL{}无须CAS登录，直接返回！", request.getServletPath());
            return true;
        }

        //获取登录用户名
        String loginName = assertion.getPrincipal().getName();
        log.info("当前登录用户名:{}", loginName);
        Principal principal = request.getUserPrincipal();
        if (request.getUserPrincipal() != null) {
            if (principal instanceof AttributePrincipal) {
                //cas传递过来的数据
                Map<String, Object> result = ((AttributePrincipal) principal).getAttributes();
                log.info("当前用户的详细信息：{}", JSONObject.toJSONString(result));

                if (UserContextUtil.getUserContext() == null) {
                    log.info("用户信息在session中不存在，初始化...");
                    Long userId = Long.valueOf(result.get("id").toString());
                    String realName = result.get("realName").toString();
                    String telephone = result.get("telephone").toString();
                    Long staffId =  Long.valueOf(result.get("staffId").toString());
                    UserContext userContext = UserContext.custom().loginName(loginName).userName(realName)
                            .telephone(telephone).userId(userId).staffId(staffId).jsonObject(JSONObject.toJSONString(result))
                            .build();
                    session.setMaxInactiveInterval(MAX_INACTIVE_SECONDS_ONE_DAY);
                    session.setAttribute(session.getId(), userContext);
                    String expandParameter=request.getQueryString();
                    log.info("用户信息已经初始化成功，expandParameter:{}", expandParameter);
                    if (StringUtils.isNotBlank(expandParameter)){
                        session.setAttribute("expand_parameter", expandParameter);
                        log.info("用户信息已经初始化成功，expand_parameter:{}存入session中！", expandParameter);
                    }
                    log.info("用户信息{}已经初始化成功，存入session中！", JSONObject.toJSONString(userContext));
                    // 跳转到登录页
                    response.sendRedirect(autoconfig.getAppServerLoginUrl());
                    return false;
                }
            }
        }

        return true;
    }
}

