package com.lesingle.edu.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.edu.common.enums.GenericStatus;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.entity.ResourceItem;
import com.lesingle.edu.entity.ResourceLibrary;
import com.lesingle.edu.mapper.ResourceItemMapper;
import com.lesingle.edu.mapper.ResourceLibraryMapper;
import com.lesingle.edu.service.ResourceLibraryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资源库服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ResourceLibraryServiceImpl extends ServiceImpl<ResourceLibraryMapper, ResourceLibrary> implements ResourceLibraryService {

    private final ResourceLibraryMapper libraryMapper;
    private final ResourceItemMapper itemMapper;

    /**
     * 分页查询资源库
     */
    @Override
    public Page<ResourceLibrary> findAllLibraries(String libraryType, String keyword, Integer page, Integer pageSize) {
        log.info("查询资源库列表，libraryType={}, keyword={}, page={}, pageSize={}", libraryType, keyword, page, pageSize);
        Page<ResourceLibrary> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<ResourceLibrary> wrapper = new LambdaQueryWrapper<>();

        if (libraryType != null && !libraryType.isEmpty()) {
            wrapper.eq(ResourceLibrary::getLibraryType, libraryType);
        }

        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(ResourceLibrary::getName, keyword);
        }

        wrapper.orderByDesc(ResourceLibrary::getCreatedAt);

        Page<ResourceLibrary> result = libraryMapper.selectPage(pageParam, wrapper);
        log.info("查询资源库列表成功，总数={}", result.getTotal());
        return result;
    }

    /**
     * 查询资源库详情
     */
    @Override
    public ResourceLibrary findLibraryById(String id) {
        log.info("查询资源库详情，id={}", id);
        ResourceLibrary library = libraryMapper.selectById(id);
        if (library == null) {
            log.warn("资源库不存在，id={}", id);
            throw new BusinessException("资源库不存在");
        }
        return library;
    }

    /**
     * 查询资源库（不存在时返回 null）
     */
    @Override
    public ResourceLibrary findLibraryByIdOrNull(String id) {
        if (id == null || id.isEmpty()) return null;
        return libraryMapper.selectById(id);
    }

    /**
     * 创建资源库
     */
    @Override
    public ResourceLibrary createLibrary(String name, String type, String description, String tenantId) {
        log.info("创建资源库，name={}, type={}, tenantId={}", name, type, tenantId);
        ResourceLibrary library = new ResourceLibrary();
        library.setName(name);
        library.setLibraryType(type);
        library.setDescription(description);
        library.setTenantId(tenantId);
        library.setStatus(GenericStatus.ACTIVE.getCode());
        library.setSortOrder(0);

        libraryMapper.insert(library);
        log.info("资源库创建成功，id={}", library.getId());
        return library;
    }

    /**
     * 更新资源库
     */
    @Override
    public ResourceLibrary updateLibrary(String id, String name, String description) {
        log.info("更新资源库，id={}, name={}, description={}", id, name, description);
        ResourceLibrary library = libraryMapper.selectById(id);
        if (library == null) {
            log.warn("资源库不存在，id={}", id);
            throw new BusinessException("资源库不存在");
        }

        if (name != null) {
            library.setName(name);
        }
        if (description != null) {
            library.setDescription(description);
        }

        libraryMapper.updateById(library);
        log.info("资源库更新成功，id={}", id);
        return library;
    }

    /**
     * 删除资源库
     */
    @Override
    public void deleteLibrary(String id) {
        log.info("删除资源库，id={}", id);
        // 先删除该资源库下的所有资源项
        LambdaQueryWrapper<ResourceItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ResourceItem::getLibraryId, id);
        itemMapper.delete(wrapper);

        libraryMapper.deleteById(id);
        log.info("资源库删除成功，id={}", id);
    }

    /**
     * 分页查询资源项目
     */
    @Override
    public Page<ResourceItem> findAllItems(String libraryId, String fileType, String keyword, Integer page, Integer pageSize) {
        log.info("查询资源项目列表，libraryId={}, fileType={}, keyword={}, page={}, pageSize={}", libraryId, fileType, keyword, page, pageSize);
        Page<ResourceItem> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<ResourceItem> wrapper = new LambdaQueryWrapper<>();

        if (libraryId != null && !libraryId.isEmpty()) {
            wrapper.eq(ResourceItem::getLibraryId, libraryId);
        }

        if (fileType != null && !fileType.isEmpty()) {
            wrapper.eq(ResourceItem::getFileType, fileType);
        }

        if (keyword != null && !keyword.isEmpty()) {
            wrapper.and(w -> w.like(ResourceItem::getTitle, keyword)
                    .or()
                    .like(ResourceItem::getDescription, keyword));
        }

        wrapper.orderByDesc(ResourceItem::getCreatedAt);

        Page<ResourceItem> result = itemMapper.selectPage(pageParam, wrapper);
        log.info("查询资源项目列表成功，总数={}", result.getTotal());
        return result;
    }

    /**
     * 查询资源项目详情
     */
    @Override
    public ResourceItem findItemById(String id) {
        log.info("查询资源项目详情，id={}", id);
        ResourceItem item = itemMapper.selectById(id);
        if (item == null) {
            log.warn("资源项目不存在，id={}", id);
            throw new BusinessException("资源项目不存在");
        }
        return item;
    }

    /**
     * 创建资源项目（数字资源）
     */
    @Override
    public ResourceItem createItem(String libraryId, String title, String fileType, String filePath,
                                   Long fileSize, String description, String tags, String tenantId) {
        log.info("创建资源项目，libraryId={}, title={}, fileType={}, fileSize={}, tenantId={}", libraryId, title, fileType, fileSize, tenantId);
        ResourceItem item = new ResourceItem();
        item.setId(null); // 确保由数据库 AUTO_INCREMENT 生成，避免主键冲突
        item.setLibraryId(libraryId); // 目标资源库 ID
        item.setTitle(title);
        item.setName(title); // 数据库 name 字段 NOT NULL，与 title 保持一致
        item.setDescription(description);
        item.setFileType(fileType);
        item.setFilePath(filePath);
        item.setFileSize(fileSize);
        item.setTags(tags);
        item.setSortOrder(0);
        item.setTenantId(tenantId);
        item.setStatus("ACTIVE");

        itemMapper.insert(item);
        log.info("资源项目创建成功，id={}", item.getId());
        return item;
    }

    /**
     * 更新资源项目（数字资源）
     */
    @Override
    public ResourceItem updateItem(String id, String title, String description, String tags) {
        log.info("更新资源项目，id={}, title={}, description={}, tags={}", id, title, description, tags);
        ResourceItem item = itemMapper.selectById(id);
        if (item == null) {
            log.warn("资源项目不存在，id={}", id);
            throw new BusinessException("资源项目不存在");
        }

        if (title != null) {
            item.setTitle(title);
        }
        if (description != null) {
            item.setDescription(description);
        }
        if (tags != null) {
            item.setTags(tags);
        }

        itemMapper.updateById(item);
        log.info("资源项目更新成功，id={}", id);
        return item;
    }

    /**
     * 删除资源项目
     */
    @Override
    public void deleteItem(String id) {
        log.info("删除资源项目，id={}", id);
        itemMapper.deleteById(id);
        log.info("资源项目删除成功，id={}", id);
    }

    /**
     * 批量删除资源项目
     */
    @Override
    public void batchDeleteItems(List<String> ids) {
        log.info("批量删除资源项目，ids={}", ids);
        itemMapper.deleteBatchIds(ids);
        log.info("批量删除资源项目成功，数量={}", ids.size());
    }

    /**
     * 获取统计数据
     */
    @Override
    public Map<String, Object> getStats() {
        log.info("获取资源库统计数据");
        Map<String, Object> stats = new HashMap<>();

        Long libraryCount = libraryMapper.selectCount(null);
        Long itemCount = itemMapper.selectCount(null);

        stats.put("totalLibraries", libraryCount);
        stats.put("totalItems", itemCount);

        // 按资源库类型统计资源数量（绘本资源、教学材料等）
        Map<String, Long> itemsByLibraryType = new HashMap<>();
        LambdaQueryWrapper<ResourceLibrary> libWrapper = new LambdaQueryWrapper<>();
        for (ResourceLibrary lib : libraryMapper.selectList(libWrapper)) {
            String type = lib.getLibraryType();
            if (type != null) {
                LambdaQueryWrapper<ResourceItem> itemWrapper = new LambdaQueryWrapper<>();
                itemWrapper.eq(ResourceItem::getLibraryId, String.valueOf(lib.getId()));
                long count = itemMapper.selectCount(itemWrapper);
                itemsByLibraryType.merge(type, count, Long::sum);
            }
        }
        stats.put("itemsByLibraryType", itemsByLibraryType);

        log.info("资源库统计数据：totalLibraries={}, totalItems={}, itemsByLibraryType={}", libraryCount, itemCount, itemsByLibraryType);
        return stats;
    }

}
