package com.fzm.mall.server.admin.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.admin.auth_center.model.AuthMenu;
import com.fzm.mall.server.admin.auth_center.service.IAuthMenuService;
import com.fzm.mall.server.admin.constant.MALLGlobalConfig;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.home_page.enums.type.AdminTypeEnum;
import com.fzm.mall.server.admin.home_page.model.Admin;
import com.fzm.mall.server.admin.home_page.service.IAdminService;
import com.fzm.mall.server.admin.repo.ResponseFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author wangp
 * @date 2021/2/26 18:10
 * @description 权限拦截
 * @since JDK 1.8
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthInterceptor implements HandlerInterceptor {

    private final ResponseFactory resFac;
    private final IAuthMenuService authMenuService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String adminId = request.getHeader("adminId");

        //放行
        if (Pattern.matches("^/malladmin/(?:homePage|merchantApply|personalInfo|sms)/.*$", requestURI)) {
            return true;
        }

        //权限认证==================================================================

        //获取登陆管理员权限
        List<AuthMenu> adminAuthMenu = authMenuService.getAdminAuthMenu(adminId);

        //判断权限是否为空
        if (CollectionUtils.isEmpty(adminAuthMenu)) {
            JSONObject.writeJSONString(response.getWriter(), resFac.getResponse(MallResponseError.NO_AUTH_ERROR));
            return false;
        }

        //权限匹配
        boolean match = adminAuthMenu.stream()
                .map(AuthMenu::getMenuUrl)
                .anyMatch(p -> Pattern.matches(p, requestURI));

        if (!match) {
            JSONObject.writeJSONString(response.getWriter(), resFac.getResponse(MallResponseError.NO_AUTH_ERROR));
            return false;
        }

        return false;
    }

}
