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

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.seer.teach.teacher.module.entity.ReadingRecordsEntity;
import com.seer.teach.teacher.module.mapper.ReadingRecordsMapper;
import com.seer.teach.teacher.service.ReadDurationsService;
import com.seer.teach.teacher.service.ReadingRecordsService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户阅读记录表 服务实现类
 * </p>
 *
 * @author Captain
 * @since 2025-06-13
 */
@Service
@RequiredArgsConstructor
public class ReadingRecordsServiceImpl extends ServiceImpl<ReadingRecordsMapper, ReadingRecordsEntity> implements ReadingRecordsService {

    private final ReadingRecordsMapper readingRecordsMapper;

    private final ReadDurationsService readDurationsService;


    /**
     * 获取用户最近阅读记录（每本书只保留最新一条）
     *
     * @param page   分页对象，用于分页查询结果
     * @param userId 用户 ID，指定要查询的用户
     * @return 返回去重后的分页阅读记录列表，每本书仅包含最新的那条记录
     */
    @Override
    public Page<ReadingRecordsEntity> getLatestReadingByUser(Page<ReadingRecordsEntity> page, Integer userId) {
        return  (Page<ReadingRecordsEntity>)  readingRecordsMapper.selectLatestReadingByUser(page, userId);
    }

    /**
     * 异步插入用户的阅读记录，并同步更新阅读时长信息
     *
     * @param userId    用户 ID
     * @param bookId    图书 ID
     * @param chapterId 章节 ID
     */
    @Async
    @Override
    public void insertRecord(Integer userId, Integer bookId, Integer chapterId) {
        // 构造新的阅读记录实体
        ReadingRecordsEntity record = new ReadingRecordsEntity();
        record.setUserId(userId);
        record.setBookId(bookId);
        record.setChapterId(chapterId);
        record.setModel(0);               // 默认模型值设为 0
        record.setAiHumanId(0);           // 默认 AI/Human 标识设为 0
        record.setLastReadTime(LocalDateTime.now());
        // 同步插入阅读时长记录
        readDurationsService.insertRecord(userId, bookId, chapterId);
        // 保存当前阅读记录到数据库
        this.save(record);
    }
}

