package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reading.platform.common.enums.ErrorCode;
import com.reading.platform.common.exception.BusinessException;
import com.reading.platform.common.util.PageUtils;
import com.reading.platform.dto.response.ResourceStatsResponse;
import com.reading.platform.entity.ResourceItem;
import com.reading.platform.entity.ResourceLibrary;
import com.reading.platform.mapper.ResourceItemMapper;
import com.reading.platform.mapper.ResourceLibraryMapper;
import com.reading.platform.service.ResourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 资源服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl implements ResourceService {

    private final ResourceLibraryMapper resourceLibraryMapper;
    private final ResourceItemMapper resourceItemMapper;

    @Override
    public List<ResourceLibrary> getLibraries(String tenantId) {
        LambdaQueryWrapper<ResourceLibrary> wrapper = new LambdaQueryWrapper<>();
        if (tenantId != null) {
            wrapper.eq(ResourceLibrary::getTenantId, tenantId);
        }
        wrapper.orderByDesc(ResourceLibrary::getCreatedAt);
        return resourceLibraryMapper.selectList(wrapper);
    }

    @Override
    public Page<ResourceItem> getItems(int pageNum, int pageSize, String libraryId, String keyword) {
        Page<ResourceItem> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ResourceItem> wrapper = new LambdaQueryWrapper<>();
        if (libraryId != null) {
            wrapper.eq(ResourceItem::getLibraryId, libraryId);
        }
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(ResourceItem::getName, keyword);
        }
        wrapper.orderByDesc(ResourceItem::getCreatedAt);
        return resourceItemMapper.selectPage(page, wrapper);
    }

    @Override
    public List<ResourceLibrary> getTenantLibraries(String tenantId) {
        LambdaQueryWrapper<ResourceLibrary> wrapper = new LambdaQueryWrapper<>();
        if (tenantId != null) {
            wrapper.eq(ResourceLibrary::getTenantId, tenantId);
        }
        wrapper.orderByDesc(ResourceLibrary::getCreatedAt);
        return resourceLibraryMapper.selectList(wrapper);
    }

    @Override
    public ResourceLibrary getLibraryById(String id) {
        ResourceLibrary lib = resourceLibraryMapper.selectById(id);
        if (lib == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "资源库不存在");
        }
        return lib;
    }

    @Override
    public ResourceLibrary createLibrary(ResourceLibrary library) {
        resourceLibraryMapper.insert(library);
        return library;
    }

    @Override
    public ResourceLibrary updateLibrary(String id, ResourceLibrary library) {
        getLibraryById(id);
        library.setId(id);
        resourceLibraryMapper.updateById(library);
        return resourceLibraryMapper.selectById(id);
    }

    @Override
    public void deleteLibrary(String id) {
        resourceLibraryMapper.deleteById(id);
    }

    @Override
    public Page<ResourceItem> getItemsByTenant(String tenantId, int pageNum, int pageSize, String libraryId, String keyword, String type) {
        Page<ResourceItem> page = PageUtils.of(pageNum, pageSize);
        LambdaQueryWrapper<ResourceItem> wrapper = new LambdaQueryWrapper<>();

        if (tenantId != null) {
            wrapper.eq(ResourceItem::getTenantId, tenantId);
        }
        if (libraryId != null) {
            wrapper.eq(ResourceItem::getLibraryId, libraryId);
        }
        if (StringUtils.hasText(keyword)) {
            wrapper.like(ResourceItem::getName, keyword);
        }
        if (StringUtils.hasText(type)) {
            wrapper.eq(ResourceItem::getType, type);
        }
        wrapper.orderByDesc(ResourceItem::getCreatedAt);
        return resourceItemMapper.selectPage(page, wrapper);
    }

    @Override
    public ResourceItem getItemById(String id) {
        ResourceItem item = resourceItemMapper.selectById(id);
        if (item == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "资源项不存在");
        }
        return item;
    }

    @Override
    public ResourceItem createItem(ResourceItem item) {
        resourceItemMapper.insert(item);
        return item;
    }

    @Override
    public ResourceItem updateItem(String id, ResourceItem item) {
        getItemById(id);
        item.setId(id);
        resourceItemMapper.updateById(item);
        return resourceItemMapper.selectById(id);
    }

    @Override
    public void deleteItem(String id) {
        resourceItemMapper.deleteById(id);
    }

    @Override
    public void batchDeleteItems(List<String> ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids) {
                deleteItem(id);
            }
        }
    }

    @Override
    public List<ResourceStatsResponse> getStats(String tenantId) {
        List<ResourceStatsResponse> stats = new ArrayList<>();

        // 资源库统计
        List<ResourceLibrary> libraries = getTenantLibraries(tenantId);
        for (ResourceLibrary library : libraries) {
            ResourceStatsResponse response = new ResourceStatsResponse();
            response.setId(library.getId().toString());
            response.setName(library.getName());
            response.setType("library");
            Long count = resourceItemMapper.selectCount(
                    new LambdaQueryWrapper<ResourceItem>().eq(ResourceItem::getLibraryId, library.getId()));
            response.setCount(Math.toIntExact(count));
            stats.add(response);
        }

        log.info("获取资源统计：tenantId={}, 资源库数量={}", tenantId, libraries.size());
        return stats;
    }
}
