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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.teacher.convert.LessonConvert;
import com.seer.teach.teacher.module.entity.LessonRecordsEntity;
import com.seer.teach.teacher.module.mapper.LessonRecordsMapper;
import com.seer.teach.teacher.service.LessonRecordsService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2025-12-02 21:29:37
 */
@Service
public class LessonRecordsServiceImpl extends ServiceImpl<LessonRecordsMapper, LessonRecordsEntity> implements LessonRecordsService {

    /**
     * 保存课程记录
     *
     * @param lessonId 课程ID
     * @param goalId 目标ID
     * @param textId 文本ID
     * @return 保存的课程记录实体
     */
    @Override
    public LessonRecordsEntity saveLessonRecord(Integer lessonId, Integer goalId, Integer textId) {
        LessonRecordsEntity record = LessonConvert.INSTANCE.toLessonRecord(lessonId, goalId, textId, LocalDateTime.now());
        this.save(record);
        return record;
    }

    /**
     * 异步更新课程记录的结束时间
     * 计算学习时长并更新数据库记录
     *
     * @param recordId 课程记录ID
     */
    @Async
    @Override
    public void updateEndTime(Integer recordId) {
        // 获取课程记录并计算学习时长
        LessonRecordsEntity record = this.getById(recordId);
        LocalDateTime now = LocalDateTime.now();
        int seconds = (int) Duration.between(record.getCreateTime(), now).getSeconds();

        // 更新结束时间和学习秒数
        this.lambdaUpdate()
                .eq(LessonRecordsEntity::getId, recordId)
                .set(LessonRecordsEntity::getEndTime, now)
                .set(LessonRecordsEntity::getStudySeconds, seconds)
                .update();
    }
}

