package com.qqchen.deploy.backend.system.service.impl;

import com.qqchen.deploy.backend.system.converter.MenuConverter;
import com.qqchen.deploy.backend.system.converter.PermissionConverter;
import com.qqchen.deploy.backend.system.entity.Menu;
import com.qqchen.deploy.backend.system.entity.Permission;
import com.qqchen.deploy.backend.framework.annotation.ServiceType;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import com.qqchen.deploy.backend.system.model.MenuDTO;
import com.qqchen.deploy.backend.system.model.PermissionDTO;
import com.qqchen.deploy.backend.system.model.query.PermissionQuery;
import com.qqchen.deploy.backend.system.repository.IMenuRepository;
import com.qqchen.deploy.backend.system.repository.IPermissionRepository;
import com.qqchen.deploy.backend.system.service.IPermissionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

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

import static com.qqchen.deploy.backend.framework.annotation.ServiceType.Type.DATABASE;

@Slf4j
@Service
@ServiceType(DATABASE)
public class PermissionServiceImpl extends BaseServiceImpl<Permission, PermissionDTO, PermissionQuery, Long> implements IPermissionService {

    @Resource
    private IPermissionRepository permissionRepository;

    @Resource
    private IMenuRepository menuRepository;

    @Resource
    private PermissionConverter permissionConverter;

    @Resource
    private MenuConverter menuConverter;

    /**
     * 覆盖单体查询方法，添加菜单信息
     */
    @Override
    public PermissionDTO findById(Long id) {
        PermissionDTO dto = super.findById(id);
        if (dto != null && dto.getMenuId() != null) {
            menuRepository.findById(dto.getMenuId()).ifPresent(menu -> 
                dto.setMenu(menuConverter.toDto(menu))
            );
        }
        return dto;
    }

    /**
     * 覆盖分页查询方法，添加菜单信息
     */
    @Override
    public Page<PermissionDTO> page(PermissionQuery query) {
        // 调用父类方法获取分页数据
        Page<PermissionDTO> page = super.page(query);
        // 填充菜单信息
        enrichWithMenuInfo(page.getContent());
        return page;
    }

    /**
     * 覆盖列表查询方法，添加菜单信息
     */
    @Override
    public List<PermissionDTO> findAll(PermissionQuery query) {
        List<PermissionDTO> list = super.findAll(query);
        enrichWithMenuInfo(list);
        return list;
    }

    @Override
    public List<PermissionDTO> listAllEnabled() {
        List<Permission> permissions = permissionRepository.findAllEnabledOrderByMenuAndSort();
        List<PermissionDTO> dtoList = permissionConverter.toDtoList(permissions);
        enrichWithMenuInfo(dtoList);
        return dtoList;
    }

    @Override
    public List<PermissionDTO> listByMenuId(Long menuId) {
        List<Permission> permissions = permissionRepository.findByMenuIdAndEnabledTrue(menuId);
        List<PermissionDTO> dtoList = permissionConverter.toDtoList(permissions);
        enrichWithMenuInfo(dtoList);
        return dtoList;
    }

    @Override
    public List<PermissionDTO> listByIds(List<Long> ids) {
        List<Permission> permissions = permissionRepository.findByIdIn(ids);
        List<PermissionDTO> dtoList = permissionConverter.toDtoList(permissions);
        enrichWithMenuInfo(dtoList);
        return dtoList;
    }

    /**
     * 为权限DTO列表填充菜单信息
     */
    private void enrichWithMenuInfo(List<PermissionDTO> permissionDTOs) {
        if (permissionDTOs == null || permissionDTOs.isEmpty()) {
            return;
        }

        // 收集所有菜单ID
        List<Long> menuIds = permissionDTOs.stream()
            .map(PermissionDTO::getMenuId)
            .filter(id -> id != null)
            .distinct()
            .collect(Collectors.toList());

        if (menuIds.isEmpty()) {
            return;
        }

        // 批量查询菜单并转换为DTO
        Map<Long, MenuDTO> menuMap = menuRepository.findAllById(menuIds).stream()
            .map(menuConverter::toDto)
            .collect(Collectors.toMap(MenuDTO::getId, menu -> menu));

        // 填充菜单信息
        permissionDTOs.forEach(dto -> {
            if (dto.getMenuId() != null) {
                dto.setMenu(menuMap.get(dto.getMenuId()));
            }
        });
    }
}