package com.house365.web.klf.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.house365.rest.context.CmConstant;
import com.house365.web.filter.ParameterRequestWrapper;

/**
 * 城市过滤器<br>
 * 增加城市信息条件
 */
public class CityFilter implements Filter {

    /**
     * 需要排除的页面字符串
     */
    private String excludedPages;

    /**
     * 需要排除的页面列表
     */
    private List<String> excludedPageList = new ArrayList<String>();

    /**
     * Default constructor.
     */
    public CityFilter() {
    }

    public void destroy() {
    }

    public void doFilter(
        ServletRequest request, ServletResponse response, FilterChain chain
    ) throws IOException, ServletException {
        boolean isExcludedPage = false;
        // 判断是否在过滤url之外
        for (String page : excludedPageList) {
            if (((HttpServletRequest) request).getRequestURI().contains(page)) {
                isExcludedPage = true;
                break;
            }
        }
        if (!isExcludedPage) {
            if (request instanceof HttpServletRequest) {
                HttpServletRequest servletRequest = (HttpServletRequest) request;
                HttpSession session = servletRequest.getSession(false);
                String cityKey = null;
                String userRole = null;
                if (null != session) {
                    Object cityIdObj = session.getAttribute(CmConstant.CITY_KEY);
                    Object userRoleObj = session.getAttribute(CmConstant.USER_ROLE);
                    userRole = userRoleObj == null ? null : userRoleObj.toString();
                    //无城市信息
                    if (null == cityIdObj) {
                        ((HttpServletResponse) response).sendError(403, "无权限访问，请重新登录");
                        return;
                    }
                    cityKey = cityIdObj.toString();
                } else {
                    ((HttpServletResponse) response).sendError(403, "无权限访问，请重新登录");
                    return;
                }
                @SuppressWarnings("unchecked") Map<String, Object> parameterMap = new HashMap<String, Object>(
                    servletRequest.getParameterMap());
                if (StringUtils.isNotEmpty(cityKey) && CmConstant.ROLE_ADMIN.equals(userRole)) {
                    //如果是超级管理员用户，则不用查城市参数
                } else {
                    parameterMap.put("search_EQ_cityKey", new String[] {cityKey});
                }
                ParameterRequestWrapper newRequest = new ParameterRequestWrapper(servletRequest, parameterMap);
                request = newRequest;
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * @param filterConfig 过滤器配置信息
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        excludedPages = filterConfig.getInitParameter("excludedPages");
        if (StringUtils.isNotEmpty(excludedPages)) {
            String[] excludedPageArray = excludedPages.split(",");
            for (String excludedPage : excludedPageArray) {
                excludedPageList.add(excludedPage);
            }
        }
        return;
    }
}
