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

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.seer.teach.common.PageListBean;
import com.seer.teach.teacher.common.req.BookChapterListReq;
import com.seer.teach.teacher.common.resp.BookChapterListTvResp;
import com.seer.teach.teacher.common.utils.TeacherUtils;
import com.seer.teach.teacher.convert.BookConvert;
import com.seer.teach.teacher.module.entity.BookChaptersEntity;
import com.seer.teach.teacher.module.mapper.BookChaptersMapper;
import com.seer.teach.teacher.service.BookChaptersService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 章节信息表 服务实现类
 * </p>
 *
 * @author Captain
 * @since 2025-06-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BookChaptersServiceImpl extends ServiceImpl<BookChaptersMapper, BookChaptersEntity> implements BookChaptersService {

    /**
     * 根据设备类型和查询参数获取书籍章节列表
     *
     * @param params 查询参数对象，包含书籍ID、分页信息等
     * @return 返回分页的书籍章节列表数据
     */
    @Override
    public PageListBean<BookChapterListTvResp> list(BookChapterListReq params) {
        // 构造分页返回
        PageListBean<BookChapterListTvResp> pageListBean = new PageListBean<>();
        Page<BookChaptersEntity> page = new Page<>(params.getPage(), params.getLimits());

        // 根据书籍ID查询章节信息，并按排序字段升序排列
        Page<BookChaptersEntity> resultPage = super.page(page,
                new LambdaQueryWrapper<BookChaptersEntity>()
                        .in(BookChaptersEntity::getBookId, params.getId())
                        .orderByAsc(BookChaptersEntity::getSort));

        List<BookChaptersEntity> records = resultPage.getRecords();
        List<BookChapterListTvResp> results = new ArrayList<>();

        // 转换章节实体为响应对象，并处理内容摘要
        records.stream().forEach(i -> {
            BookChapterListTvResp result = BookConvert.INSTANCE.toBookChapterTvResp(i);
            result.setContent(TeacherUtils.getBriefCOntent(result.getContent()));
            results.add(result);
        });

        // 设置分页信息
        pageListBean.setList(results);
        pageListBean.setTotal(resultPage.getTotal());
        pageListBean.setPage(resultPage.getCurrent());
        pageListBean.setTotalPage(resultPage.getPages());
        pageListBean.setPageSize(params.getLimits());
        return pageListBean;
    }

}
