package weaver.interfaces.htsc.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.K1810007
 * @version: 1.0
 * @CreateDate: 2022-08-22
 * @Description: 门户登录拦截器，获取header的iv-user登录OA系统，不做其他动作
 * * @ModifyLog:
 *
 **/


@Slf4j
public class HtscLoginBeforeFilter implements Filter {
    private ServletContext application;
    private List<String> unCheckLogoutList  = new ArrayList<String>();
    public BaseBean baseBean = new BaseBean();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.application = filterConfig.getServletContext();
        initUnCheckUrl();
    }

    /***
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException
    {
        log.info("unCheckLogoutList:"+unCheckLogoutList.size());
        initUnCheckUrl();

        String path = GCONST.getContextPath();

//        List<String> unCheckLogoutLists  = new ArrayList<String>();
//        String unCheckLogoutUrlInit = baseBean.getPropValue("htsc_sso_session_filter","unchecklogouturl");
//        String[] dataCheckLogoutUrl = unCheckLogoutUrlInit.split(";") ;
//        for(int i=0;i<dataCheckLogoutUrl.length;i++){
//            if(dataCheckLogoutUrl[i].startsWith(path)){
//                unCheckLogoutLists.add(dataCheckLogoutUrl[i]);
//            }else{
//                unCheckLogoutLists.add(path+dataCheckLogoutUrl[i]);
//            }
//        }

        HtscLoginUtil htscLoginUtil = new HtscLoginUtil();
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;

        //请求地址
        String getRequestUri = httpServletRequest.getRequestURI();
        String pathLowerCase = getRequestUri.toLowerCase();

        String cur = ".cur";
        String ico = ".ico";
        String css = ".css";
        String htm = ".htm";
        String png = ".png";
        String jpg = ".jpg";
        String gif = ".gif";

        boolean isExcludedPage = false;
        boolean exclude = (pathLowerCase.endsWith(cur)) || (pathLowerCase.endsWith(ico)) || (pathLowerCase.endsWith(css)) || (pathLowerCase.endsWith(htm))  || (pathLowerCase.endsWith(png)) || (pathLowerCase.endsWith(jpg)) || (pathLowerCase.endsWith(gif)) ;
        if (exclude){
            isExcludedPage = true;
        }
        if(!isExcludedPage){
            if (unCheckLogoutList.contains(getRequestUri) || unCheckLogoutList.contains(path + getRequestUri)) {
                isExcludedPage = true;
            }
        }

        log.info("HtscLoginBeforeFilter--getRequestUri:"+getRequestUri+" -----isExcludedPage:"+isExcludedPage);

        if (isExcludedPage) {
            // 如果发现是css或者js文件，直接放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }else{
            //sessionid 是否为空
            User user = (User) httpServletRequest.getSession(true).getAttribute("weaver_user@bean");
            if (user == null)
            {
                String htusercode = Util.null2String(httpServletRequest.getHeader("iv-user"));
                String unAuthenticated = "Unauthenticated";
                if (!unAuthenticated.equalsIgnoreCase(htusercode) && StringUtils.isNotEmpty(htusercode)) {
                    RecordSet rs = new RecordSet();
                    String userId = "";
                    String sql = " select id from hrmresource where loginid=?";
                    rs.executeQuery(sql, new Object[]{htusercode});
                    if (rs.next()) {
                        userId = Util.null2String(rs.getString("id"));
                        log.info("HtscLoginFilter", "Success get user id "+userId);
                    }
                    if (StringUtils.isNotEmpty(userId)) {
                        htscLoginUtil.userSessionFilter(htusercode, httpServletRequest, httpServletResponse, application);
                    }
                }
            }
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }

    /**
     *
     */
    @Override
    public void destroy() {

    }


    public void initUnCheckUrl()
    {
        if(unCheckLogoutList.isEmpty())
        {
            String path = GCONST.getContextPath();
            BaseBean baseBean = new BaseBean();
            unCheckLogoutList = new ArrayList<String>();
            // 获取配置文件htsc_sso_session_filter.properties里的过滤的url地址
            String unCheckLogoutInit = baseBean.getPropValue("htsc_sso_session_filter","unchecklogouturl");
            if(StringUtils.isNotEmpty(unCheckLogoutInit)){
                String[] dataCheckLogoutUrl = unCheckLogoutInit.split(";") ;
                for(int i=0;i<dataCheckLogoutUrl.length;i++){
                    if(dataCheckLogoutUrl[i].startsWith(path)){
                        unCheckLogoutList.add(dataCheckLogoutUrl[i]);
                    }else{
                        unCheckLogoutList.add(path+dataCheckLogoutUrl[i]);
                    }
                }
            }
        }
    }
}
