package weaver.interfaces.htsc.filter;

import com.api.login.util.LoginUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.login.VerifyLogin;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.K1810007
 * @version: 1.0
 * @CreateDate: 2022-08-22
 * @Description: 门户登录拦截器，公共的方法
 * * @ModifyLog:
 *
 **/

public class HtscLoginUtil{

    /***
     *
     * @param path
     * @param getRequestUri
     * @param unCheckSessionUrlList
     * @param unCheckUrlList
     * @param unCheckSessionUrlDevList
     * @return
     */
    public boolean checkUrlFilter(String path,String getRequestUri,List<String> unCheckSessionUrlList,List<String> unCheckSsoUrlList,List<String> unCheckUrlList,List<String> unCheckSessionUrlDevList){
        boolean isExcludedPage = false;
        String pathLowerCase = getRequestUri.toLowerCase();
        String cur = ".cur";
        String ico = ".ico";
        String css = ".css";
        String js = ".js";
        String htm = ".htm";
        String html = ".html";
        String png = ".png";
        String jpg = ".jpg";
        String gif = ".gif";

        boolean exclude = (pathLowerCase.endsWith(cur)) || (pathLowerCase.endsWith(ico)) || (pathLowerCase.endsWith(css)) || (pathLowerCase.endsWith(js)) || (pathLowerCase.endsWith(htm)) || (pathLowerCase.endsWith(html)) || (pathLowerCase.endsWith(png)) || (pathLowerCase.endsWith(jpg)) || (pathLowerCase.endsWith(gif)) ;

        if (exclude) {
            isExcludedPage = true;
        }
        if (!isExcludedPage)
        {
            if (unCheckUrlList.contains(getRequestUri) || unCheckUrlList.contains(path + getRequestUri)) {
                isExcludedPage = true;
            }
        }

        if (!isExcludedPage) {
            if (unCheckSessionUrlList.contains(getRequestUri) || unCheckSessionUrlList.contains(path + getRequestUri)) {
                isExcludedPage = true;
            }
        }

        if (!isExcludedPage) {
            if (unCheckSsoUrlList.contains(getRequestUri) || unCheckSsoUrlList.contains(path + getRequestUri)) {
                isExcludedPage = true;
            }
        }

        if(!isExcludedPage)
        {
            if(unCheckSessionUrlDevList.contains(getRequestUri) || unCheckSessionUrlDevList.contains(path+getRequestUri)){
                isExcludedPage = true;
            }
        }

        if (isExcludedPage) {
            if(getRequestUri.contains("ViewRequestForwardSPA.jsp")){
                isExcludedPage = false;
            }
        }

        return isExcludedPage;
    }


    /****
     *
     * @param htusercode
     * @param request
     * @param response
     * @param application
     */
    public void userSessionFilter(String htusercode, HttpServletRequest request, HttpServletResponse response, ServletContext application){

        boolean isMutiLangua = Util.isEnableMultiLang();
        //系统使用语言,未使用多语言的用户默认为中文。
        int isLanguId = 7;
        String languId = "7";
        if (isMutiLangua) {
            isLanguId = Util.getIntValue(request.getParameter("islanguid"), 0);
            //如何未选择，则默认系统使用语言为简体中文
            if (isLanguId == 0) {
                isLanguId = 7;
            }
            languId = String.valueOf(isLanguId);
            Cookie syslanid = new Cookie("Systemlanguid", languId);
            syslanid.setMaxAge(-1);
            syslanid.setPath("/");
            response.addCookie(syslanid);
        }

        RecordSet rs = new RecordSet();
        User newUser = null;
        String loginUserId = "" ;
        String loginName = "" ;
        String sql = " select * from hrmresource where loginid= ? ";
        rs.executeQuery(sql,new Object[]{htusercode});
        if (rs.next())
        {
            newUser = new User();
            loginUserId = Util.null2String(rs.getInt("id"));
            loginName = Util.null2String(rs.getInt("lastname"));
            newUser.setUid(rs.getInt("id"));
            newUser.setLoginid(rs.getString("loginid"));
            newUser.setPwd(rs.getString("password"));
            newUser.setFirstname(rs.getString("firstname"));
            newUser.setLastname(rs.getString("lastname"));
            newUser.setAliasname(rs.getString("aliasname"));
            newUser.setTitle(rs.getString("title"));
            newUser.setTitlelocation(rs.getString("titlelocation"));
            newUser.setSex(rs.getString("sex"));
            newUser.setPwd(rs.getString("password"));
            String languageIdWeaver = rs.getString("systemlanguage");
            newUser.setLanguage(Util.getIntValue(languageIdWeaver, 7));
            if (!languId.equalsIgnoreCase(languageIdWeaver) && isMutiLangua) {
                User.setUserLang(rs.getInt("id"), Util.getIntValue(languId, 7));
                languageIdWeaver = languId;

            }
            newUser.setTelephone(rs.getString("telephone"));
            newUser.setMobile(rs.getString("mobile"));
            newUser.setMobilecall(rs.getString("mobilecall"));
            newUser.setEmail(rs.getString("email"));
            newUser.setCountryid(rs.getString("countryid"));
            newUser.setLocationid(rs.getString("locationid"));
            newUser.setResourcetype(rs.getString("resourcetype"));

            newUser.setStartdate(rs.getString("startdate"));
            newUser.setEnddate(rs.getString("enddate"));
            newUser.setContractdate(rs.getString("contractdate"));
            newUser.setJobtitle(rs.getString("jobtitle"));
            newUser.setJobgroup(rs.getString("jobgroup"));
            newUser.setJobactivity(rs.getString("jobactivity"));
            newUser.setJoblevel(rs.getString("joblevel"));
            newUser.setSeclevel(rs.getString("seclevel"));
            newUser.setUserDepartment(Util.getIntValue(rs.getString("departmentid"), 0));
            newUser.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
            newUser.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
            newUser.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
            newUser.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
            newUser.setManagerid(rs.getString("managerid"));
            newUser.setAssistantid(rs.getString("assistantid"));
            newUser.setPurchaselimit(rs.getString("purchaselimit"));
            newUser.setCurrencyid(rs.getString("currencyid"));
            newUser.setLastlogindate(rs.getString("currentdate"));
            newUser.setLogintype("1");
            newUser.setAccount(rs.getString("account"));
            newUser.setLoginip(request.getRemoteAddr());
            String weaverLoginType = Util.null2String(request.getSession(true).getAttribute("weaver_login_type"));
            if("".equals(weaverLoginType)){
                weaverLoginType = "1";
            }
            request.getSession(true).setAttribute("weaver_login_type", weaverLoginType);
            request.getSession(true).setAttribute("weaver_user@bean", newUser);
            request.getSession(true).setAttribute("rtxlogin", "1");

            Util.setCookie(response, "loginidweaver", newUser.getUID() + "", -1);
            Util.setCookie(response, "languageidweaver", Util.null2s(languageIdWeaver, "7"), -1);


            HttpSession session = request.getSession(true);
            session.removeAttribute("validateRand");
            session.setAttribute("isie", Util.null2String(request.getParameter("isie")));
            session.setAttribute("browser_isie", Util.null2String(request.getParameter("isie")));

            Calendar today = Calendar.getInstance();
            String currentdate = Util.add0(today.get(1), 4) + "-" + Util.add0(today.get(2) + 1, 2) + "-" + Util.add0(today.get(5), 2);
            char separater = Util.getSeparator();
            rs.execute("HrmResource_UpdateLoginDate", rs.getString("id") + separater + currentdate);

            boolean moreAccountLanding = GCONST.getMOREACCOUNTLANDING();
            if (moreAccountLanding) {
                if (newUser.getUID() != 1) {
                    VerifyLogin verifyLogin = new VerifyLogin();
                    List accounts = verifyLogin.getAccountsById(newUser.getUID());
                    request.getSession(true).setAttribute("accounts", accounts);
                }
                Util.setCookie(response, "loginidweaver", newUser.getUID()+"", -1);
            }

            Map userSessions = (Map) application.getAttribute("userSessions");
            String uId = String.valueOf(newUser.getUID());
            if (userSessions == null) {
                userSessions = new java.util.concurrent.ConcurrentHashMap();
            }
            List slist = (List) userSessions.get(uId);
            slist = slist == null ? new ArrayList() : slist;
            slist.add(session);
            userSessions.put(uId, slist);
            application.setAttribute("userSessions", userSessions);
        }

        if(!"".equals(loginUserId))
        {
            LoginUtil.recordLogin(Util.getIntValue(loginUserId),loginName,request.getRemoteAddr());
        }
    }
}
