package org.xyzh.news.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.dto.resource.TbResource;
import org.xyzh.common.dto.resource.TbResourceTag;
import org.xyzh.common.dto.resource.TbTag;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.dto.usercenter.TbUserCollection;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.common.vo.ResourceVO;
import org.xyzh.common.vo.TagVO;
import org.xyzh.news.mapper.ResourceMapper;
import org.xyzh.news.mapper.ResourceTagMapper;
import org.xyzh.system.utils.LoginUtil;
import org.xyzh.api.news.resource.ResourceService;
import org.xyzh.api.usercenter.collection.UserCollectionService;

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

/**
 * @description 资源服务实现类
 * @filename NCResourceServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-15
 */
@Service
public class NCResourceServiceImpl implements ResourceService {

    private static final Logger logger = LoggerFactory.getLogger(NCResourceServiceImpl.class);

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceTagMapper resourceTagMapper;

    @Autowired
    private UserCollectionService userCollectionService;

    @Override
    public ResultDomain<TbResource> getResourceList(TbResource filter) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            if (filter == null) {
                filter = new TbResource();
            }
            List<TbResource> list = resourceMapper.selectResources(filter);
            resultDomain.success("获取资源列表成功", list);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取资源列表异常: {}", e.getMessage(), e);
            resultDomain.fail("获取资源列表失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResource> getResourcePage(TbResource filter, PageParam pageParam) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            if (filter == null) {
                filter = new TbResource();
            }
            
            List<TbResource> list = resourceMapper.selectResourcesPage(filter, pageParam);
            long total = resourceMapper.countResources(filter);
            pageParam.setTotalElements(total);
            pageParam.setTotalPages((int) Math.ceil((double) total / pageParam.getPageSize()));
            resultDomain.success("获取资源分页成功", new PageDomain<TbResource>(pageParam, list));
            return resultDomain;
        }
        catch (Exception e) {
            logger.error("获取资源分页异常: {}", e.getMessage(), e);
            resultDomain.fail("获取资源分页失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<ResourceVO> getResourceById(String resourceID) {
        ResultDomain<ResourceVO> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }
            ResourceVO resourceVO = new ResourceVO();
            resourceVO.setResource(resource);
            TbResourceTag filter = new TbResourceTag();
            filter.setResourceID(resourceID);
            List<TagVO> tags = resourceTagMapper.selectResourceTags(filter);
            if (tags != null && !tags.isEmpty()) {
                resourceVO.setTags(tags.stream().map(TagVO::getTag).collect(Collectors.toList()));
            } else {
                resourceVO.setTags(new ArrayList<>());
            }

            resultDomain.success("获取资源详情成功", resourceVO);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取资源详情异常: {}", e.getMessage(), e);
            resultDomain.fail("获取资源详情失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<ResourceVO> createResource(ResourceVO resourceVO) {
        ResultDomain<ResourceVO> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (resourceVO == null || !StringUtils.hasText(resourceVO.getResource().getTitle())) {
                resultDomain.fail("资源标题不能为空");
                return resultDomain;
            }

            // 检查标题是否已存在
            int count = resourceMapper.countByTitle(resourceVO.getResource().getTitle(), null);
            if (count > 0) {
                resultDomain.fail("资源标题已存在");
                return resultDomain;
            }

            // 设置默认值
            if (resourceVO.getResource().getID() == null) {
                resourceVO.getResource().setID(IDUtils.generateID());
            }
            if (resourceVO.getResource().getResourceID() == null) {
                resourceVO.getResource().setResourceID(IDUtils.generateID());
            }
            resourceVO.getResource().setCreateTime(new Date());
            resourceVO.getResource().setUpdateTime(new Date());
            resourceVO.getResource().setDeleted(false);

            // 设置默认状态和计数
            if (resourceVO.getResource().getStatus() == null) {
                resourceVO.getResource().setStatus(0); // 默认草稿状态
            }
            if (resourceVO.getResource().getViewCount() == null) {
                resourceVO.getResource().setViewCount(0);
            }
            if (resourceVO.getResource().getLikeCount() == null) {
                resourceVO.getResource().setLikeCount(0);
            }
            if (resourceVO.getResource().getCollectCount() == null) {
                resourceVO.getResource().setCollectCount(0);
            }
            if (resourceVO.getResource().getIsRecommend() == null) {
                resourceVO.getResource().setIsRecommend(false);
            }
            if (resourceVO.getResource().getIsBanner() == null) {
                resourceVO.getResource().setIsBanner(false);
            }

            // 插入数据库
            int result = resourceMapper.insertResource(resourceVO.getResource());
            // 插入资源标签
            if (resourceVO.getTags() != null && resourceVO.getTags().size() > 0) {
                List<TbResourceTag> resourceTagList = new ArrayList<>();
                for (TbTag tag : resourceVO.getTags()) {
                    TbResourceTag resourceTag = new TbResourceTag();
                    resourceTag.setResourceID(resourceVO.getResource().getID());
                    resourceTag.setTagID(tag.getID());
                    resourceTagList.add(resourceTag);
                }
                int resourceTagResult = resourceTagMapper.batchInsertResourceTags(resourceTagList);
                if (resourceTagResult <= 0) {
                    result = 0;
                }
            }

            if (result > 0) {
                logger.info("创建资源成功: {}", resourceVO.getResource().getTitle());
                resultDomain.success("创建资源成功", resourceVO);
                return resultDomain;
            } else {
                resultDomain.fail("创建资源失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("创建资源异常: {}", e.getMessage(), e);
            resultDomain.fail("创建资源失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<ResourceVO> updateResource(ResourceVO resourceVO) {
        ResultDomain<ResourceVO> resultDomain = new ResultDomain<>();
        TbResource resource = resourceVO.getResource();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        resource.setUpdater(user.getID());
        try {
            // 参数验证
            if (resource == null || !StringUtils.hasText(resource.getResourceID())) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 检查资源是否存在
            TbResource existing = resourceMapper.selectById(resource.getResourceID());
            if (existing == null || existing.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 如果修改了标题，检查标题是否已被使用
            if (StringUtils.hasText(resource.getTitle()) && !resource.getTitle().equals(existing.getTitle())) {
                int count = resourceMapper.countByTitle(resource.getTitle(), resource.getResourceID());
                if (count > 0) {
                    resultDomain.fail("资源标题已存在");
                    return resultDomain;
                }
            }
            Date now = new Date();
            // 原始tags
            TbResourceTag filter = new TbResourceTag();
            filter.setResourceID(resource.getResourceID());
            List<TagVO> originalTagVOs = resourceTagMapper.selectResourceTags(filter);
            List<TbResourceTag> originalTags = originalTagVOs.stream().map(TagVO::getResourceTag).collect(Collectors.toList());
            // 当前tags
            List<TbTag> currentTags = resourceVO.getTags();
            // 新增tags
            List<TbTag> tagsToAdd = currentTags.stream()
                .filter(tag -> originalTags.stream().noneMatch(originalTag -> originalTag.getTagID().equals(tag.getID())))
                .collect(Collectors.toList());
            // 删除tags
            List<TbResourceTag> tagsToDelete = originalTags.stream()
                .filter(originalTag -> currentTags.stream().noneMatch(tag -> tag.getID().equals(originalTag.getTagID())))
                .collect(Collectors.toList());
            
            resourceTagMapper.batchDeleteResourceTags(tagsToDelete.stream().map(TbResourceTag::getID).collect(Collectors.toList()));
            resourceTagMapper.batchInsertResourceTags(tagsToAdd.stream().map(tag -> {
                TbResourceTag resourceTag = new TbResourceTag();
                resourceTag.setResourceID(resource.getResourceID());
                resourceTag.setTagID(tag.getID());
                resourceTag.setID(IDUtils.generateID());
                resourceTag.setCreator(user.getID());
                resourceTag.setCreateTime(now);
                return resourceTag;
            }).collect(Collectors.toList()));
            
            // 更新时间
            resource.setUpdateTime(now);

            // 更新数据库
            int result = resourceMapper.updateResource(resource);
            if (result > 0) {
                logger.info("更新资源成功: {}", resource.getResourceID());
                // 重新查询返回完整数据
                TbResource updated = resourceMapper.selectById(resource.getResourceID());                
                ResourceVO updatedResourceVO = new ResourceVO();
                updatedResourceVO.setResource(updated);
                updatedResourceVO.setTags(currentTags);
                resultDomain.success("更新资源成功", updatedResourceVO);
                return resultDomain;
            } else {
                resultDomain.fail("更新资源失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新资源异常: {}", e.getMessage(), e);
            resultDomain.fail("更新资源失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> deleteResource(String resourceID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 物理删除
            int result = resourceMapper.deleteResource(resource);
            if (result > 0) {
                logger.info("删除资源成功: {}", resourceID);
                resultDomain.success("删除资源成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("删除资源失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("删除资源异常: {}", e.getMessage(), e);
            resultDomain.fail("删除资源失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResource> updateResourceStatus(String resourceID, Integer status) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }
            if (status == null) {
                resultDomain.fail("状态不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 更新状态
            resource.setStatus(status);
            resource.setUpdateTime(new Date());

            int result = resourceMapper.updateResource(resource);
            if (result > 0) {
                logger.info("更新资源状态成功: {}", resourceID);
                // 重新查询返回完整数据
                TbResource updated = resourceMapper.selectById(resource.getID());
                resultDomain.success("更新资源状态成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("更新资源状态失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("更新资源状态异常: {}", e.getMessage(), e);
            resultDomain.fail("更新资源状态失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResource> publishResource(String resourceID) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 更新状态为已发布
            resource.setStatus(1);
            resource.setPublishTime(new Date());
            resource.setUpdateTime(new Date());

            int result = resourceMapper.updateResource(resource);
            if (result > 0) {
                logger.info("发布资源成功: {}", resourceID);
                // 重新查询返回完整数据
                TbResource updated = resourceMapper.selectByResourceId(resource.getID());
                resultDomain.success("发布资源成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("发布资源失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("发布资源异常: {}", e.getMessage(), e);
            resultDomain.fail("发布资源失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResource> unpublishResource(String resourceID) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 更新状态为下架
            resource.setStatus(2);
            resource.setUpdateTime(new Date());

            int result = resourceMapper.updateResource(resource);
            if (result > 0) {
                logger.info("下架资源成功: {}", resourceID);
                // 重新查询返回完整数据
                TbResource updated = resourceMapper.selectByResourceId(resource.getID());
                resultDomain.success("下架资源成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("下架资源失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("下架资源异常: {}", e.getMessage(), e);
            resultDomain.fail("下架资源失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<Boolean> incrementViewCount(String resourceID) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            // 参数验证 
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            int result = resourceMapper.incrementViewCount(resourceID);
            if (result > 0) {
                logger.info("增加资源浏览次数成功: {}", resourceID);
                // 重新查询返回完整数据
                resultDomain.success("增加浏览次数成功", true);
                return resultDomain;
            } else {
                resultDomain.fail("增加浏览次数失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("增加资源浏览次数异常: {}", e.getMessage(), e);
            resultDomain.fail("增加浏览次数失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResource> incrementLikeCount(String resourceID) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 增加点赞次数
            Integer currentCount = resource.getLikeCount() != null ? resource.getLikeCount() : 0;
            resource.setLikeCount(currentCount + 1);
            resource.setUpdateTime(new Date());

            int result = resourceMapper.updateResource(resource);
            if (result > 0) {
                logger.info("增加资源点赞次数成功: {}", resourceID);
                // 重新查询返回完整数据
                TbResource updated = resourceMapper.selectById(resource.getID());
                resultDomain.success("增加点赞次数成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("增加点赞次数失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("增加资源点赞次数异常: {}", e.getMessage(), e);
            resultDomain.fail("增加点赞次数失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResource> resourceCollect(TbUserCollection collection) {
        String resourceID = collection.getCollectionID();
        Integer collectionValue = collection.getCollectionValue();
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("请先登录");
            return resultDomain;
        }
        collection.setUserID(user.getID());
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }
            if (collectionValue != 1 && collectionValue != -1) {
                resultDomain.fail("收藏值错误");
                return resultDomain;
            }
            ResultDomain<Boolean> isCollected = userCollectionService.isCollected(user.getID(), collection.getCollectionType(), resourceID);
            TbResource resource = new TbResource();
            resource.setResourceID(resourceID);
            if (isCollected.isSuccess() && isCollected.getData() && collectionValue == 1) {
                resultDomain.success("已收藏", resource);
                return resultDomain;
            }
            else if (isCollected.isSuccess() && isCollected.getData() && collectionValue == -1) {
                ResultDomain<Boolean> removeCollection = userCollectionService.removeCollection(collection);
                if (removeCollection.isSuccess()) {
                    resourceMapper.updateResourceCollectCount(resourceID, -1);
                    resultDomain.success("已取消收藏", resource);
                    return resultDomain;
                } else {
                    resultDomain.fail("取消收藏失败");
                    return resultDomain;
                }
            }else if (isCollected.isSuccess() && !isCollected.getData() && collectionValue == 1) {
                collection.setID(IDUtils.generateID());
                collection.setCreateTime(new Date());
                ResultDomain<TbUserCollection> addCollection = userCollectionService.addCollection(collection);
                if (addCollection.isSuccess() && addCollection.getData() != null) {
                    resourceMapper.updateResourceCollectCount(resourceID, 1);
                    resultDomain.success("已收藏", resource);
                    return resultDomain;
                } else {
                    resultDomain.fail("收藏失败");
                    return resultDomain;
                }
            }else {
                resultDomain.success("未收藏", resource);
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("增加资源收藏次数异常: {}", e.getMessage(), e);
            resultDomain.fail("增加收藏次数失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResource> setResourceRecommend(String resourceID, Boolean isRecommend) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }
            if (isRecommend == null) {
                resultDomain.fail("推荐状态不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 更新推荐状态
            resource.setIsRecommend(isRecommend);
            resource.setUpdateTime(new Date());

            int result = resourceMapper.updateResource(resource);
            if (result > 0) {
                logger.info("设置资源推荐状态成功: {} -> {}", resourceID, isRecommend);
                // 重新查询返回完整数据
                TbResource updated = resourceMapper.selectById(resource.getID());
                resultDomain.success("设置推荐状态成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("设置推荐状态失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("设置资源推荐状态异常: {}", e.getMessage(), e);
            resultDomain.fail("设置推荐状态失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDomain<TbResource> setResourceBanner(String resourceID, Boolean isBanner) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(resourceID)) {
                resultDomain.fail("资源ID不能为空");
                return resultDomain;
            }
            if (isBanner == null) {
                resultDomain.fail("轮播状态不能为空");
                return resultDomain;
            }

            // 查询资源
            TbResource resource = resourceMapper.selectByResourceId(resourceID);
            if (resource == null || resource.getDeleted()) {
                resultDomain.fail("资源不存在");
                return resultDomain;
            }

            // 更新轮播状态
            resource.setIsBanner(isBanner);
            resource.setUpdateTime(new Date());

            int result = resourceMapper.updateResource(resource);
            if (result > 0) {
                logger.info("设置资源轮播状态成功: {} -> {}", resourceID, isBanner);
                // 重新查询返回完整数据
                TbResource updated = resourceMapper.selectById(resource.getID());
                resultDomain.success("设置轮播状态成功", updated);
                return resultDomain;
            } else {
                resultDomain.fail("设置轮播状态失败");
                return resultDomain;
            }
        } catch (Exception e) {
            logger.error("设置资源轮播状态异常: {}", e.getMessage(), e);
            resultDomain.fail("设置轮播状态失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResource> getRecommendResources(Integer limit) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 创建过滤条件，查询推荐资源
            TbResource filter = new TbResource();
            filter.setIsRecommend(true);
            filter.setStatus(1); // 只查询已发布的
            
            List<TbResource> list = resourceMapper.selectResources(filter);
            
            // 如果指定了limit，截取列表
            if (limit != null && limit > 0 && list != null && list.size() > limit) {
                list = list.subList(0, limit);
            }

            resultDomain.success("获取推荐资源列表成功", list);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取推荐资源列表异常: {}", e.getMessage(), e);
            resultDomain.fail("获取推荐资源列表失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResource> getBannerResources(Integer limit) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 创建过滤条件，查询轮播资源
            TbResource filter = new TbResource();
            filter.setIsBanner(true);
            filter.setStatus(1); // 只查询已发布的
            
            List<TbResource> list = resourceMapper.selectResources(filter);
            
            // 如果指定了limit，截取列表
            if (limit != null && limit > 0 && list != null && list.size() > limit) {
                list = list.subList(0, limit);
            }

            resultDomain.success("获取轮播资源列表成功", list);
            return resultDomain;
        } catch (Exception e) {
            logger.error("获取轮播资源列表异常: {}", e.getMessage(), e);
            resultDomain.fail("获取轮播资源列表失败: " + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbResource> searchResources(String keyword, String categoryID, Integer status) {
        ResultDomain<TbResource> resultDomain = new ResultDomain<>();
        try {
            // 参数验证
            if (!StringUtils.hasText(keyword)) {
                resultDomain.fail("搜索关键词不能为空");
                return resultDomain;
            }

            // 先按关键词搜索
            List<TbResource> list = resourceMapper.searchByKeyword(keyword);
            
            // 如果指定了分类ID，进行过滤
            if (StringUtils.hasText(categoryID) && list != null) {
                list.removeIf(resource -> !categoryID.equals(resource.getCategoryID()));
            }
            
            // 如果指定了状态，进行过滤
            if (status != null && list != null) {
                list.removeIf(resource -> !status.equals(resource.getStatus()));
            }

            resultDomain.success("搜索资源成功", list);
            return resultDomain;
        } catch (Exception e) {
            logger.error("搜索资源异常: {}", e.getMessage(), e);
            resultDomain.fail("搜索资源失败: " + e.getMessage());
            return resultDomain;
        }
    }
}
