package com.zhentao.config;

import com.zhentao.entity.AdminUser;
import com.zhentao.entity.Permission;
import com.zhentao.mapper.PermissionMapper;
import com.zhentao.service.AuthService;
import com.zhentao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 权限拦截器
 * 根据Controller路径判断用户是否有权限访问
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {
    
    @Autowired
    private AuthService authService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只拦截Controller方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        // 获取请求路径和方法
        String requestPath = request.getRequestURI();
        String method = request.getMethod();
        
        // 排除登录接口
        if (requestPath.contains("/admin/auth/login") || requestPath.contains("/admin/auth/logout")) {
            return true;
        }
        
        // 获取token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未授权，请先登录\"}");
            return false;
        }
        
        // 获取用户信息
        AdminUser user = authService.getUserByToken(token);
        if (user == null) {
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期，请重新登录\"}");
            return false;
        }
        
        // 检查用户是否是超级管理员
        boolean isSuperAdmin = userService.isSuperAdmin(user.getId());
        
        // 超级管理员拥有所有权限
        if (isSuperAdmin) {
            return true;
        }
        
        // 查询用户的所有权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(user.getId());
        
        // 检查是否有匹配的权限
        boolean hasPermission = permissions.stream().anyMatch(permission -> {
            String permissionPath = permission.getPath();
            String permissionMethod = permission.getMethod();
            
            // 检查方法是否匹配
            boolean methodMatch = "ALL".equals(permissionMethod) || method.equals(permissionMethod);
            if (!methodMatch) {
                return false;
            }
            
            // 支持通配符匹配
            if (permissionPath.contains("**")) {
                // /admin/user/** 匹配 /admin/user/xxx/yyy
                String prefix = permissionPath.substring(0, permissionPath.length() - 2);
                if (requestPath.startsWith(prefix)) {
                    return true;
                }
            } else if (permissionPath.contains("*")) {
                // /admin/user/* 匹配 /admin/user/xxx (单层)
                String pattern = permissionPath.replace("*", "[^/]+");
                if (requestPath.matches(pattern)) {
                    return true;
                }
            } else {
                // 精确匹配
                if (requestPath.equals(permissionPath)) {
                    return true;
                }
            }
            
            return false;
        });
        
        if (!hasPermission) {
            response.setStatus(403);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":403,\"message\":\"没有权限访问该资源\"}");
            return false;
        }
        
        return true;
    }
}

