package com.xdap.self_development.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.xdap.self_development.domain.enums.AuthorizationClassEnum;
import com.xdap.self_development.domain.view.MenuParamView;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.AuthService;
import com.xdap.self_development.service.ModelRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private ModelRoleService modelRoleService;

    @Override
    public void checkUserAuthorization(String userId, AuthorizationClassEnum classEnum) {
        List<MenuParamView> menuParamViews = modelRoleService.selectPersByUser(userId);
        // 过滤检查是否为管理员
        List<MenuParamView> isAdmin = menuParamViews.stream().filter(item ->
                        item.getIsAdmin() != null && item.getIsAdmin() == 1)
                .collect(Collectors.toList());
        if (!isAdmin.isEmpty()) {
            return;
        }
        // 过滤检查是否有相关权限
        List<MenuParamView> collected = menuParamViews.stream()
                .filter(view -> StringUtils.isNotBlank(view.getPermissionPath()))
                .filter(view -> {
                    String permissionPath = view.getPermissionPath();
                    String[] pathSegments = permissionPath.split("/");
                    if (pathSegments.length == 0) {
                        return false;
                    }
                    String firstPath = pathSegments[0];
                    String viewPer = view.getParameterPer();
                    String requirePer = classEnum.getPermissionPer();
                    String requirePath = classEnum.getPermissionPath();
                    
                    int viewPerLevel = convertPermissionLevel(viewPer);
                    int requirePerLevel = convertPermissionLevel(requirePer);
                    
                    return firstPath.endsWith(requirePath)
                            && viewPerLevel >= requirePerLevel;
                })
                .collect(Collectors.toList());

        if (collected.isEmpty()) {
            throw new CommonException("权限不足，无法执行此操作");
        }
    }
    
    private int convertPermissionLevel(String per) {
        if (per == null || per.isEmpty()) {
            return 0;
        }
        if ("查看".equals(per) || "1".equals(per)) {
            return 1;
        }
        if ("编辑".equals(per) || "2".equals(per)) {
            return 2;
        }
        try {
            return Integer.parseInt(per);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    @Override
    public void checkUserHasPermission(String userId, String permission) {
        List<MenuParamView> menuParamViews = modelRoleService.selectPersByUser(userId);
        // 过滤检查是否为管理员
        List<MenuParamView> isAdmin = menuParamViews.stream().filter(item ->
                        item.getIsAdmin() != null && item.getIsAdmin() == 1)
                .collect(Collectors.toList());
        if (!isAdmin.isEmpty()) {
            return;
        }
        // 过滤检查是否有相关权限
        List<MenuParamView> collected = menuParamViews.stream()
                .filter(view -> StringUtils.isNotBlank(view.getPermissionPath()))
                .filter(view -> {
                    String permissionPath = view.getPermissionPath();
                    String[] pathSegments = permissionPath.split("/");
                    if (pathSegments.length == 0) {
                        return false;
                    }
                    String firstPath = pathSegments[0];
                    return firstPath.endsWith(permission);
                })
                .collect(Collectors.toList());

        if (collected.isEmpty()) {
            throw new CommonException("您没有" + permission + "的操作权限");
        }
    }
}
