package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.entity.Permission;
import com.zhentao.mapper.PermissionMapper;
import com.zhentao.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限服务实现
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Override
    public Permission createPermission(Permission permission) {
        // 检查权限编码是否已存在
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("permission_code", permission.getPermissionCode());
        Permission existPermission = permissionMapper.selectOne(wrapper);
        if (existPermission != null) {
            throw new RuntimeException("权限编码已存在");
        }
        
        permission.setStatus(1); // 默认启用
        if (permission.getMethod() == null || permission.getMethod().isEmpty()) {
            permission.setMethod("ALL");
        }
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        
        permissionMapper.insert(permission);
        return permission;
    }
    
    @Override
    public Page<Permission> getPermissionList(Integer pageNum, Integer pageSize, String keyword) {
        Page<Permission> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("permission_name", keyword)
                    .or().like("permission_code", keyword)
                    .or().like("path", keyword));
        }
        
        wrapper.orderByAsc("sort_order", "create_time");
        
        return permissionMapper.selectPage(page, wrapper);
    }
    
    @Override
    public Permission getPermissionById(Integer permissionId) {
        return permissionMapper.selectById(permissionId);
    }
    
    @Override
    public boolean updatePermission(Permission permission) {
        permission.setUpdateTime(LocalDateTime.now());
        if (permission.getMethod() == null || permission.getMethod().isEmpty()) {
            permission.setMethod("ALL");
        }
        return permissionMapper.updateById(permission) > 0;
    }
    
    @Override
    public boolean deletePermission(Integer permissionId) {
        return permissionMapper.deleteById(permissionId) > 0;
    }
    
    @Override
    public List<Permission> getUserPermissions(Integer userId) {
        return permissionMapper.selectPermissionsByUserId(userId);
    }
    
    @Override
    public boolean hasPermission(Integer userId, String path, String method) {
        List<Permission> permissions = getUserPermissions(userId);
        
        for (Permission permission : permissions) {
            String permissionPath = permission.getPath();
            String permissionMethod = permission.getMethod();
            
            // 检查路径是否匹配（支持通配符）
            if (pathMatches(permissionPath, path)) {
                // 检查方法是否匹配
                if ("ALL".equals(permissionMethod) || 
                    permissionMethod.equalsIgnoreCase(method)) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * 检查路径是否匹配（支持通配符）
     */
    private boolean pathMatches(String pattern, String path) {
        // 完全匹配
        if (pattern.equals(path)) {
            return true;
        }
        
        // 通配符匹配：/admin/user/** 匹配 /admin/user/list, /admin/user/add 等
        if (pattern.endsWith("/**")) {
            String prefix = pattern.substring(0, pattern.length() - 3);
            return path.startsWith(prefix);
        }
        
        // 通配符匹配：/admin/** 匹配所有 /admin/ 开头的路径
        if (pattern.endsWith("**")) {
            String prefix = pattern.substring(0, pattern.length() - 2);
            return path.startsWith(prefix);
        }
        
        return false;
    }
    
    @Override
    public List<Permission> getAllPermissionsTree() {
        List<Permission> allPermissions = permissionMapper.selectList(
            new QueryWrapper<Permission>().eq("status", 1)
                .orderByAsc("sort_order", "create_time")
        );
        
        // 构建树形结构
        List<Permission> rootPermissions = allPermissions.stream()
            .filter(p -> p.getParentId() == null || p.getParentId() == 0)
            .collect(Collectors.toList());
        
        for (Permission root : rootPermissions) {
            buildTree(root, allPermissions);
        }
        
        return rootPermissions;
    }
    
    /**
     * 递归构建权限树
     */
    private void buildTree(Permission parent, List<Permission> allPermissions) {
        List<Permission> children = allPermissions.stream()
            .filter(p -> parent.getId().equals(p.getParentId()))
            .collect(Collectors.toList());
        
        // 这里可以添加children字段到Permission实体，暂时简化处理
        for (Permission child : children) {
            buildTree(child, allPermissions);
        }
    }
}

