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

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
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.common.cache.dto.CorrectResultDTO;
import com.seer.teach.common.dto.mq.StringDTO;
import com.seer.teach.common.enums.im.CommandTopicTagEnum;
import com.seer.teach.common.enums.im.ImMqTopicEnum;
import com.seer.teach.iot.api.UserDeviceServiceApi;
import com.seer.teach.teacher.common.llm.sse.req.LlmAiCorrectReq;
import com.seer.teach.teacher.common.req.GradingTasksPageListReq;
import com.seer.teach.teacher.common.resp.GradingTasksPageListResp;
import com.seer.teach.teacher.common.utils.TeacherUtils;
import com.seer.teach.teacher.convert.GradingTaskConvert;
import com.seer.teach.teacher.module.entity.GradingTasksEntity;
import com.seer.teach.teacher.module.mapper.GradingTasksMapper;
import com.seer.teach.teacher.mq.ImMqProducer;
import com.seer.teach.teacher.service.GradingTasksService;
import com.seer.teach.teacher.service.LlmSseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

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

import static cn.dev33.satoken.stp.StpUtil.getLoginIdAsInt;

/**
 * 批改任务服务实现类
 * 提供上传批改图片、调用AI进行批改、获取历史批改记录等功能。
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GradingTasksServiceImpl extends ServiceImpl<GradingTasksMapper, GradingTasksEntity> implements GradingTasksService {

    private final UserDeviceServiceApi userDeviceServiceApi;

    private final ImMqProducer imMqProducer;


    private final LlmSseService llmSseService;


    @Override
    public Flux<CorrectResultDTO> correct(String imageUrl) {
        Integer userId = 1;
        // 生成会话ID
        Integer sessionId = TeacherUtils.generateSessionId(userId, imageUrl);
        // 构造请求对象
        LlmAiCorrectReq req = LlmAiCorrectReq.requestObject(sessionId, userId, imageUrl);
        // 存储本次批改任务记录
        GradingTasksEntity entity = GradingTaskConvert.INSTANCE.toEntity(req);
        save(entity);
        // 发起AI批改请求
        return llmSseService.aiCorrect(req);
    }

    /**
     * 请求用户上传图片
     * <p>
     * 该方法会获取当前登录用户ID和设备信息，然后发送MQ消息通知用户上传图片。
     * 主要用于AI纠错功能的图片上传提醒。
     * </p>
     */
    @Override
    public void pleaseUploadImage() {
        // 获取当前登录用户ID
        int userId = getLoginIdAsInt();

        // 根据用户ID获取设备信息
        String device = userDeviceServiceApi.getDeviceByUserId(userId);

        log.info("发送请上传图片MQ消息，userId: {}, device: {}", userId, device);

        // 发送MQ消息到命令主题，请用户上传图片
        imMqProducer.sendMsg(ImMqTopicEnum.COMMAND, CommandTopicTagEnum.ENTER_AI_CORRECTION.getTag(), device, JSONUtil.toJsonStr(StringDTO.ping()));

        log.info("请上传图片MQ消息发送成功，userId: {}, device: {}", userId, device);
    }

    /**
     * 分页查询用户的批改任务列表
     *
     * @param param  查询条件封装对象，包括分页信息
     * @return 返回分页后的批改任务列表及分页元数据
     */
    @Override
    public PageListBean<GradingTasksPageListResp> getGradingTasks(GradingTasksPageListReq param) {
        // 根据设备号获取用户ID
        Integer userId = StpUtil.getLoginIdAsInt();
        // 初始化MyBatis Plus分页对象
        Page<GradingTasksEntity> page = new Page<>(param.getPage(), param.getLimits());
        // 查询数据库中的批改任务记录
        Page<GradingTasksEntity> pageResult = this.getBaseMapper().selectPage(page,
                new LambdaQueryWrapper<GradingTasksEntity>()
                        .eq(GradingTasksEntity::getUserId, userId)
                        .orderByDesc(GradingTasksEntity::getCreateTime));

        List<GradingTasksPageListResp> respList = new ArrayList<>();
        for (int i = 0; i < pageResult.getRecords().size(); i++) {
            GradingTasksEntity entity = pageResult.getRecords().get(i);
            GradingTasksPageListResp resp = new GradingTasksPageListResp();
            // 复制属性值
            BeanUtils.copyProperties(entity, resp);
            // 判断创建时间是否是今天以决定显示格式
            if (TeacherUtils.isToday(entity.getCreateTime())) {
                resp.setCreateTime(TeacherUtils.formatTimestampToTime(entity.getCreateTime()));
                // 设置第一条为当前使用项（仅第一页第一项）
                if (i == 0 && param.getPage() == 1) {
                    resp.setIsUsed(1);
                }
            } else {
                resp.setCreateTime(TeacherUtils.formatTimestampToDate(entity.getCreateTime()));
            }
            respList.add(resp);
        }

        // 封装分页结果返回
        PageListBean<GradingTasksPageListResp> pageListBean = new PageListBean<>();
        pageListBean.setList(respList);
        pageListBean.setTotal(pageResult.getTotal());
        pageListBean.setPage(pageResult.getCurrent());
        pageListBean.setTotalPage(pageResult.getPages());
        pageListBean.setPageSize(param.getLimits());
        return pageListBean;
    }

}
