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 HtscLoginFilter implements Filter {
    private ServletContext application;

    private List<String> unCheckSessionUrlList = new ArrayList<String>();
    private List<String> unCheckSsoUrlList = new ArrayList<String>();
    private List<String> unCheckUrlList = new ArrayList<String>();
    private List<String> unCheckSessionUrlDevList = new ArrayList<String>();
    private HtscLoginUtil htscLoginUtil = new HtscLoginUtil();
    private 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 {
        String path = GCONST.getContextPath();

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //请求地址
        String getRequestUri = request.getRequestURI();
        String htusercode = Util.null2String(request.getHeader("iv-user"));

        boolean isExcludedPage = htscLoginUtil.checkUrlFilter(path, getRequestUri, unCheckSessionUrlList, unCheckSsoUrlList, unCheckUrlList, unCheckSessionUrlDevList);

        baseBean.infoLog("HtscLoginFilter", "HtscLoginFilter----getRequestURI：" + getRequestUri + "  isExcludedPage:" + isExcludedPage + " htusercode：" + htusercode);

        if (isExcludedPage) {
            //在过滤url之外
            filterChain.doFilter(request, response);
        } else {
            String xRequestedWith = "x-requested-with";
            if (StringUtils.isNotBlank(request.getHeader(xRequestedWith))) {
                request.setCharacterEncoding("UTF-8");
            }
            //sessionid 是否为空
            User user = (User) request.getSession(true).getAttribute("weaver_user@bean");
            if (user == null) {
                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"));
                        baseBean.infoLog("HtscLoginFilter", "Success get user id "+userId);
                    }
                    if (StringUtils.isNotEmpty(userId)) {
                        htscLoginUtil.userSessionFilter(htusercode, request, response, application);
                    }
                }
            }

            User userlogin = (User) request.getSession(true).getAttribute("weaver_user@bean");
            if (userlogin != null) {
                String portalUrl1 = path;
                String portalUrl2 = path + "/";
//                String portalUrl3 = path + "/wui/index.html";
                boolean existed = (portalUrl1.equals(getRequestUri)) || (portalUrl2.equals(getRequestUri) );
                if (existed) {
                    response.sendRedirect(path + "/wui/index.html?#/main");
                    return;
                }
            }
            filterChain.doFilter(request, response);
        }
    }

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

    }



    public void initUnCheckUrl() {
        String path = GCONST.getContextPath();

        unCheckUrlList = new ArrayList<String>();
        // 产品原生配置文件，内容为PC端无需登录的API列表，生效范围：所有拦截器
        String unCheckUrlInit = baseBean.getPropValue("weaver_session_filter", "uncheckurl");
        baseBean.infoLog("HtscLoginFilter", "uncheckurl配置的url:" + unCheckUrlInit);
        if(StringUtils.isNotEmpty(unCheckUrlInit)){
            String[] dataCheckUrl = unCheckUrlInit.split(";");
            for (int i = 0; i < dataCheckUrl.length; i++) {
                if (dataCheckUrl[i].startsWith(path)) {
                    unCheckUrlList.add(dataCheckUrl[i]);
                } else {
                    unCheckUrlList.add(path + dataCheckUrl[i]);
                }
            }
        }


        unCheckSessionUrlList = new ArrayList<String>();
        //  产品原生配置文件，内容为PC和移动端无需登录的API列表，生效范围：所有拦截器
        String unCheckSessionUrlInit = baseBean.getPropValue("weaver_session_filter", "unchecksessionurl");
        baseBean.infoLog("HtscLoginFilter", "unchecksessionurl配置的url:" + unCheckSessionUrlInit);
        if(StringUtils.isNotEmpty(unCheckSessionUrlInit)){
            String[] dataCheckSessionUrl = unCheckSessionUrlInit.split(";");
            for (int i = 0; i < dataCheckSessionUrl.length; i++) {
                if (dataCheckSessionUrl[i].startsWith(path)) {
                    unCheckSessionUrlList.add(dataCheckSessionUrl[i]);
                } else {
                    unCheckSessionUrlList.add(path + dataCheckSessionUrl[i]);
                }
            }
        }


        unCheckSsoUrlList = new ArrayList<String>();
        // 华泰自定义的配置文件，内容为无需登录的API列表，生效范围：HtscLoginFilter
        String unCheckSsoUrlInit = baseBean.getPropValue("htsc_sso_session_filter", "uncheckssourl");
        baseBean.infoLog("HtscLoginFilter", "uncheckssourl配置的url:" + unCheckSsoUrlInit);
        if(StringUtils.isNotEmpty(unCheckSsoUrlInit)){
            String[] dataCheckSsoUrl = unCheckSsoUrlInit.split(";");
            for (int i = 0; i < dataCheckSsoUrl.length; i++) {
                if (dataCheckSsoUrl[i].startsWith(path)) {
                    unCheckSsoUrlList.add(dataCheckSsoUrl[i]);
                } else {
                    unCheckSsoUrlList.add(path + dataCheckSsoUrl[i]);
                }
            }
        }


        unCheckSessionUrlDevList = new ArrayList<String>();
        // 华泰自定义的配置文件，内容为无需登录的API列表，生效范围：所有拦截器
        String unCheckSessionUrlDevInit = baseBean.getPropValue("weaver_session_filter_dev", "unchecksessionurl");
        baseBean.infoLog("HtscLoginFilter", "unchecksessionurl_dev配置的url:" + unCheckSessionUrlDevInit);
        if(StringUtils.isNotEmpty(unCheckSessionUrlDevInit)){
            String[] dataCheckSessionDevUrl = unCheckSessionUrlDevInit.split(";");
            for (int i = 0; i < dataCheckSessionDevUrl.length; i++) {
                if (dataCheckSessionDevUrl[i].startsWith(path)) {
                    unCheckSessionUrlDevList.add(dataCheckSessionDevUrl[i]);
                } else {
                    unCheckSessionUrlDevList.add(path + dataCheckSessionDevUrl[i]);
                }
            }
        }

    }
}

