package com.erp.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.permission.dto.*;
import com.erp.permission.entity.Permission;
import com.erp.permission.exception.BusinessException;
import com.erp.permission.repository.PermissionRepository;
import com.erp.permission.service.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {
    
    private final PermissionRepository permissionRepository;
    
    @Override
    public PermissionListResponse listPermissions(String group, String keyword) {
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        
        if (group != null && !group.isBlank()) {
            wrapper.eq(Permission::getGroupName, group);
        }
        
        if (keyword != null && !keyword.isBlank()) {
            wrapper.like(Permission::getName, keyword);
        }
        
        wrapper.orderByAsc(Permission::getGroupName)
               .orderByAsc(Permission::getSort);
        
        List<Permission> permissions = permissionRepository.selectList(wrapper);
        
        // 转换为DTO
        List<PermissionDTO> list = permissions.stream()
                .map(this::toDTO)
                .collect(Collectors.toList());
        
        // 按分组组织
        Map<String, List<PermissionDTO>> grouped = permissions.stream()
                .collect(Collectors.groupingBy(
                        p -> p.getGroupName() != null ? p.getGroupName() : "未分组",
                        Collectors.mapping(this::toDTO, Collectors.toList())
                ));
        
        return PermissionListResponse.builder()
                .list(list)
                .grouped(grouped)
                .build();
    }
    
    @Override
    public List<String> listGroups() {
        return permissionRepository.findAllGroupNames();
    }
    
    @Override
    public PermissionDTO getPermission(Long id) {
        Permission permission = permissionRepository.selectById(id);
        if (permission == null) {
            throw new BusinessException(404, "权限不存在");
        }
        return toDTO(permission);
    }
    
    @Override
    @Transactional
    public PermissionDTO createPermission(CreatePermissionRequest request) {
        // 检查slug是否已存在
        if (permissionRepository.existsBySlug(request.getCode())) {
            throw new BusinessException(400, "权限标识已存在");
        }
        
        Permission permission = Permission.builder()
                .name(request.getName())
                .slug(request.getCode())
                .groupName(request.getGroup())
                .description(request.getDescription())
                .sort(request.getSort() != null ? request.getSort() : 0)
                .build();
        
        permissionRepository.insert(permission);
        log.info("创建权限成功: {}", permission.getSlug());
        
        return toDTO(permission);
    }
    
    @Override
    @Transactional
    public PermissionDTO updatePermission(Long id, UpdatePermissionRequest request) {
        Permission permission = permissionRepository.selectById(id);
        if (permission == null) {
            throw new BusinessException(404, "权限不存在");
        }
        
        if (request.getName() != null) {
            permission.setName(request.getName());
        }
        if (request.getGroup() != null) {
            permission.setGroupName(request.getGroup());
        }
        if (request.getDescription() != null) {
            permission.setDescription(request.getDescription());
        }
        if (request.getSort() != null) {
            permission.setSort(request.getSort());
        }
        
        permissionRepository.updateById(permission);
        log.info("更新权限成功: {}", permission.getSlug());
        
        return toDTO(permission);
    }
    
    @Override
    @Transactional
    public void deletePermission(Long id) {
        Permission permission = permissionRepository.selectById(id);
        if (permission == null) {
            throw new BusinessException(404, "权限不存在");
        }
        
        // 删除角色权限关联
        permissionRepository.deleteById(id);
        log.info("删除权限成功: {}", permission.getSlug());
    }
    
    @Override
    @Transactional
    public BatchCreateResult batchCreatePermissions(BatchCreatePermissionRequest request) {
        int created = 0;
        
        for (BatchCreatePermissionRequest.PermissionItem item : request.getPermissions()) {
            if (!permissionRepository.existsBySlug(item.getCode())) {
                Permission permission = Permission.builder()
                        .name(item.getName())
                        .slug(item.getCode())
                        .groupName(item.getGroup())
                        .description(item.getDescription())
                        .sort(item.getSort() != null ? item.getSort() : 0)
                        .build();
                
                permissionRepository.insert(permission);
                created++;
            }
        }
        
        log.info("批量创建权限: 成功创建 {} 个", created);
        return BatchCreateResult.builder().created(created).build();
    }
    
    @Override
    public List<String> getPermissionSlugsByRoleId(Long roleId) {
        return permissionRepository.findByRoleId(roleId).stream()
                .map(Permission::getSlug)
                .collect(Collectors.toList());
    }
    
    @Override
    public Set<Long> getPermissionIdsBySlugs(List<String> slugs) {
        if (slugs == null || slugs.isEmpty()) {
            return Collections.emptySet();
        }
        
        return permissionRepository.findBySlugs(slugs).stream()
                .map(Permission::getId)
                .collect(Collectors.toSet());
    }
    
    @Override
    public boolean existsBySlug(String slug) {
        return permissionRepository.existsBySlug(slug);
    }
    
    /**
     * 转换为DTO
     */
    private PermissionDTO toDTO(Permission permission) {
        return PermissionDTO.builder()
                .id(permission.getId())
                .name(permission.getName())
                .code(permission.getSlug())
                .group(permission.getGroupName())
                .description(permission.getDescription())
                .createTime(permission.getCreatedAt())
                .build();
    }
}
