package com.seer.teach.teacher.service.registry.smartRead.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.teacher.SmartReadEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.teacher.common.req.BookPageReq;
import com.seer.teach.teacher.common.resp.AppBookInfoResp;
import com.seer.teach.teacher.convert.BookConvert;
import com.seer.teach.teacher.module.entity.BooksEntity;
import com.seer.teach.teacher.module.entity.ReadingRecordsEntity;
import com.seer.teach.teacher.service.ReadBookService;
import com.seer.teach.teacher.service.registry.smartRead.SmartReadHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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


@Service
@Slf4j
@RequiredArgsConstructor
public class RecentReadBookHandlerImpl implements SmartReadHandler {

    private final ReadBookService readBookService;

    @Override
    public Integer getType() {
        return SmartReadEnum.RECENT_READ.getType();
    }

    /**
     * 获取用户的书籍列表信息
     * @param userId 用户ID
     * @param param 分页请求参数，包含页码和每页数量
     * @return 返回分页的书籍信息列表
     */
    @Override
    public PageListBean<AppBookInfoResp> getBookList(Integer userId, BookPageReq param) {
        // 创建分页对象
        Page<ReadingRecordsEntity> page = new Page<>(param.getPage(), param.getLimits());
        // 查询用户最新的阅读记录
        Page<ReadingRecordsEntity> pageResult = readBookService.getLatestReadingByUser(page, userId);
        List<ReadingRecordsEntity> records = pageResult.getRecords();
        AssertUtils.notEmpty(records, ResultCodeEnum.NO_READING_RECORD);
        // 提取阅读记录中的书籍ID列表
        List<Integer> bookIds = records.stream()
                .map(ReadingRecordsEntity::getBookId)
                .collect(Collectors.toList());
        // 根据书籍ID列表查询书籍详细信息
        List<BooksEntity> books = readBookService.getBookByIds(bookIds);
        // 转换书籍实体为响应对象
        List<AppBookInfoResp> bookInfoList = BookConvert.INSTANCE.toBookInfoList(books);
        // 构建书籍ID到书籍信息的映射关系，用于保持原始顺序
        Map<Integer, AppBookInfoResp> infoMap = bookInfoList.stream()
                .collect(Collectors.toMap(AppBookInfoResp::getId, v -> v));
        // 按照原始阅读记录的顺序重新排列书籍信息
        List<AppBookInfoResp> orderedList = bookIds.stream()
                .map(infoMap::get)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 构造分页结果对象
        PageListBean<AppBookInfoResp> bean = new PageListBean<>();
        bean.setPage(pageResult.getCurrent());
        bean.setPageSize(pageResult.getSize());
        bean.setTotalPage(pageResult.getPages());
        bean.setTotal(pageResult.getTotal());
        bean.setList(orderedList);
        return bean;
    }
}
