package com.example.demo.service;

import com.example.demo.model.DataRule;
import com.example.demo.model.Permission;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 权限管理服务。
 * <p>实现基于角色的权限分配、菜单权限控制、按钮权限控制及数据权限分级管控。</p>
 */
@Service
public class PermissionService {

    private final Map<Long, Permission> permissionMap = new ConcurrentHashMap<>();
    private final AtomicLong permIdCounter = new AtomicLong(1);
    private final Map<Long, List<Long>> rolePermissionMap = new ConcurrentHashMap<>();
    private final Map<Long, DataRule> dataRuleMap = new ConcurrentHashMap<>();

    public PermissionService() {
        // 菜单权限
        long m1 = permIdCounter.getAndIncrement();
        permissionMap.put(m1, new Permission(m1, "用户管理", "user:manage", "menu", 0L));
        long m2 = permIdCounter.getAndIncrement();
        permissionMap.put(m2, new Permission(m2, "角色管理", "role:manage", "menu", 0L));
        long m3 = permIdCounter.getAndIncrement();
        permissionMap.put(m3, new Permission(m3, "业务管理", "business:manage", "menu", 0L));
        long m4 = permIdCounter.getAndIncrement();
        permissionMap.put(m4, new Permission(m4, "统计分析", "stat:view", "menu", 0L));
        // 按钮权限
        long b1 = permIdCounter.getAndIncrement();
        permissionMap.put(b1, new Permission(b1, "新增用户", "user:add", "button", m1));
        long b2 = permIdCounter.getAndIncrement();
        permissionMap.put(b2, new Permission(b2, "编辑用户", "user:edit", "button", m1));
        long b3 = permIdCounter.getAndIncrement();
        permissionMap.put(b3, new Permission(b3, "删除用户", "user:delete", "button", m1));
        long b4 = permIdCounter.getAndIncrement();
        permissionMap.put(b4, new Permission(b4, "提交业务", "business:submit", "button", m3));

        // 为角色1（超级管理员）分配所有权限
        rolePermissionMap.put(1L, new ArrayList<>(permissionMap.keySet()));

        // 数据权限规则
        dataRuleMap.put(1L, new DataRule(1L, 1L, "all", null));
        dataRuleMap.put(2L, new DataRule(2L, 2L, "self", null));
    }

    /**
     * 分配角色权限。
     *
     * @requirement(name="基于角色的权限分配", id="SRS-F-04-001")
     * 通过角色-权限关联向用户授予权限。
     */
    public void assignRolePermission(Long roleId, List<Long> permissionIds) {
        rolePermissionMap.put(roleId, new ArrayList<>(permissionIds));
    }

    /**
     * 获取用户菜单权限。
     *
     * @requirement(name="菜单权限", id="SRS-F-04-002")
     * 根据用户角色获取可见的菜单树。
     */
    public List<Permission> getUserMenus(Long roleId) {
        List<Long> permIds = rolePermissionMap.getOrDefault(roleId, new ArrayList<>());
        List<Permission> result = new ArrayList<>();
        for (Long pid : permIds) {
            Permission p = permissionMap.get(pid);
            if (p != null && "menu".equals(p.getType())) {
                result.add(p);
            }
        }
        return result;
    }

    /**
     * 获取用户按钮权限。
     *
     * @requirement(name="按钮权限", id="SRS-F-04-003")
     * 根据用户角色获取页面操作按钮的权限标识。
     */
    public List<String> getUserButtons(Long roleId) {
        List<Long> permIds = rolePermissionMap.getOrDefault(roleId, new ArrayList<>());
        List<String> codes = new ArrayList<>();
        for (Long pid : permIds) {
            Permission p = permissionMap.get(pid);
            if (p != null && "button".equals(p.getType())) {
                codes.add(p.getPermissionCode());
            }
        }
        return codes;
    }

    /**
     * 获取数据权限规则。
     *
     * @requirement(name="数据权限分级管控", id="SRS-F-04-004")
     * 根据角色获取数据权限规则，控制用户可访问的数据范围。
     */
    public DataRule getDataRule(Long roleId) {
        DataRule rule = dataRuleMap.get(roleId);
        if (rule == null) {
            return new DataRule(null, roleId, "self", null);
        }
        return rule;
    }

    /**
     * 查询所有权限列表。
     */
    public List<Permission> listAllPermissions() {
        return new ArrayList<>(permissionMap.values());
    }
}
