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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.iot.api.UserDeviceServiceApi;
import com.seer.teach.teacher.common.utils.TeacherUtils;
import com.seer.teach.teacher.convert.ChatLogConvert;
import com.seer.teach.teacher.module.entity.ChatLogsEntity;
import com.seer.teach.teacher.module.mapper.ChatLogsMapper;
import com.seer.teach.teacher.service.ChatLogsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2025-09-10 13:45:42
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatLogsServiceImpl extends ServiceImpl<ChatLogsMapper, ChatLogsEntity> implements ChatLogsService {


    private final UserDeviceServiceApi userDeviceServiceApi;

    @Override
    @Async("logExecutor")
    public void saveChatLog(String userQuestion, String llmAnswers, Integer userId) {
        log.info("记录 用户模型对话 UserId ：{} Question:{} Answer:{}", userId, userQuestion, llmAnswers);
        ChatLogsEntity saveData = ChatLogConvert.INSTANCE.toChatLogEntity(userId, userQuestion, llmAnswers);
        save(saveData);
    }

    @Override
    public HashMap<String, String> list(String device) {
        Integer userId = userDeviceServiceApi.getUserIdByDevice(device);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime oneDayAgo = now.minusDays(1);
        List<ChatLogsEntity> logs = list(new LambdaQueryWrapper<ChatLogsEntity>()
                .eq(ChatLogsEntity::getUserId, userId)
                .ge(ChatLogsEntity::getCreateTime, oneDayAgo)
                .le(ChatLogsEntity::getCreateTime, now));
        String answer = logs.stream().map(ChatLogsEntity::getModelAnswer).collect(Collectors.joining("\n\n"));
        HashMap<String, String> results = new HashMap<>();
        results.put("result", answer);
        return results;
    }

    @Override
    public List<ChatLogsEntity> getChatLogIn15minutes(Integer userId) {
        LocalDateTime fifteenMinutesAgo = TeacherUtils.minutesAgo(15);
        LocalDateTime now = TeacherUtils.now();
        return list(new LambdaQueryWrapper<ChatLogsEntity>()
                .eq(ChatLogsEntity::getUserId, userId)
                .between(ChatLogsEntity::getCreateTime, fifteenMinutesAgo, now)
                .orderByAsc(ChatLogsEntity::getCreateTime));
    }
}
