package com.haha.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.vo.Result;
import com.haha.entity.DataPermission;
import com.haha.mapper.DataPermissionMapper;
import com.haha.service.DataPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据权限服务实现类
 */
@Slf4j
@Service
public class DataPermissionServiceImpl extends ServiceImpl<DataPermissionMapper, DataPermission> implements DataPermissionService {

    @Autowired
    private DataPermissionMapper dataPermissionMapper;

    @Override
    public Result<List<DataPermission>> getAllPermissions() {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectAllEnabled();
            return Result.success("查询成功", permissions);
        } catch (Exception e) {
            log.error("查询所有权限失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, List<DataPermission>>> getPermissionsGroupByModule() {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectAllGroupByModule();
            
            Map<String, List<DataPermission>> groupedPermissions = new LinkedHashMap<>();
            for (DataPermission permission : permissions) {
                String moduleName = permission.getModuleName();
                if (!groupedPermissions.containsKey(moduleName)) {
                    groupedPermissions.put(moduleName, new ArrayList<>());
                }
                groupedPermissions.get(moduleName).add(permission);
            }
            
            return Result.success("查询成功", groupedPermissions);
        } catch (Exception e) {
            log.error("查询分组权限失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Map<String, Object>>> getPermissionsTree() {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectAllGroupByModule();
            
            Map<String, Map<String, Object>> moduleMap = new LinkedHashMap<>();
            long moduleId = -1;
            
            for (DataPermission permission : permissions) {
                String moduleCode = permission.getModuleCode();
                String moduleName = permission.getModuleName();
                
                if (!moduleMap.containsKey(moduleCode)) {
                    moduleId--;
                    Map<String, Object> moduleNode = new LinkedHashMap<>();
                    moduleNode.put("id", moduleId);
                    moduleNode.put("name", moduleName);
                    moduleNode.put("children", new ArrayList<Map<String, Object>>());
                    moduleMap.put(moduleCode, moduleNode);
                }
                
                Map<String, Object> permissionNode = new LinkedHashMap<>();
                permissionNode.put("id", permission.getId());
                permissionNode.put("name", permission.getPermissionName());
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> children = (List<Map<String, Object>>) moduleMap.get(moduleCode).get("children");
                children.add(permissionNode);
            }
            
            List<Map<String, Object>> tree = new ArrayList<>(moduleMap.values());
            return Result.success("查询成功", tree);
        } catch (Exception e) {
            log.error("查询权限树失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<DataPermission>> getPermissionsByModule(String moduleCode) {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectByModuleCode(moduleCode);
            return Result.success("查询成功", permissions);
        } catch (Exception e) {
            log.error("查询模块权限失败, moduleCode={}", moduleCode, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<DataPermission>> getPermissionsByRoleId(Long roleId) {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectByRoleId(roleId);
            return Result.success("查询成功", permissions);
        } catch (Exception e) {
            log.error("查询角色权限失败, roleId={}", roleId, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<String>> getPermissionCodesByRoleId(Long roleId) {
        try {
            List<DataPermission> permissions = dataPermissionMapper.selectByRoleId(roleId);
            List<String> codes = new ArrayList<>();
            for (DataPermission permission : permissions) {
                codes.add(permission.getPermissionCode());
            }
            return Result.success("查询成功", codes);
        } catch (Exception e) {
            log.error("查询角色权限编码失败, roleId={}", roleId, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Override
    public List<String> getPermissionCodesByRoleIds(List<Long> roleIds) {
        if (roleIds == null || roleIds.isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return dataPermissionMapper.selectPermissionCodesByRoleIds(roleIds);
        } catch (Exception e) {
            log.error("查询角色权限编码失败, roleIds={}", roleIds, e);
            return new ArrayList<>();
        }
    }

    @Override
    public boolean existsByPermissionCode(String permissionCode) {
        DataPermission permission = dataPermissionMapper.selectByPermissionCode(permissionCode);
        return permission != null && permission.getStatus() == 1;
    }
}
