package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.edu.dto.request.TaskFeedbackRequest;
import com.lesingle.edu.dto.response.TaskFeedbackResponse;
import com.lesingle.edu.entity.TaskCompletion;
import com.lesingle.edu.entity.TaskFeedback;
import com.lesingle.edu.entity.Teacher;
import com.lesingle.edu.mapper.TaskCompletionMapper;
import com.lesingle.edu.mapper.TaskFeedbackMapper;
import com.lesingle.edu.service.TaskFeedbackService;
import com.lesingle.edu.service.TeacherService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 任务评价 Service 实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskFeedbackServiceImpl extends ServiceImpl<TaskFeedbackMapper, TaskFeedback>
        implements TaskFeedbackService {

    private final TaskCompletionMapper taskCompletionMapper;
    private final TeacherService teacherService;

    @Override
    @Transactional
    public TaskFeedbackResponse createOrUpdateFeedback(Long completionId, TaskFeedbackRequest request) {
        return createOrUpdateFeedback(completionId, request, null);
    }

    /**
     * 创建或更新评价（指定教师ID）
     * @param completionId 完成记录ID
     * @param request 评价请求
     * @param teacherId 教师ID（从当前登录用户获取）
     * @return 评价响应
     */
    @Transactional
    public TaskFeedbackResponse createOrUpdateFeedback(Long completionId, TaskFeedbackRequest request, Long teacherId) {
        // 获取完成记录
        TaskCompletion completion = taskCompletionMapper.selectById(completionId);
        if (completion == null) {
            throw new RuntimeException("完成记录不存在");
        }

        // 检查是否已评价
        Optional<TaskFeedback> existingFeedback = baseMapper.findByCompletionId(completionId);

        TaskFeedback feedback;
        if (existingFeedback.isPresent()) {
            // 更新评价
            feedback = existingFeedback.get();
            feedback.setResult(request.getResult());
            feedback.setRating(request.getRating());
            feedback.setComment(request.getComment());
            feedback.setUpdatedAt(LocalDateTime.now());
            this.updateById(feedback);
            log.info("更新评价成功：completionId={}", completionId);
        } else {
            // 创建新评价
            feedback = new TaskFeedback();
            feedback.setCompletionId(completionId);
            feedback.setTaskId(completion.getTaskId());
            feedback.setStudentId(completion.getStudentId());
            feedback.setTeacherId(teacherId);
            feedback.setResult(request.getResult());
            feedback.setRating(request.getRating());
            feedback.setComment(request.getComment());
            feedback.setCreatedAt(LocalDateTime.now());
            feedback.setUpdatedAt(LocalDateTime.now());
            this.save(feedback);
            log.info("创建评价成功：completionId={}, teacherId={}", completionId, teacherId);
        }

        // 更新完成记录状态为已评价
        completion.setStatus("REVIEWED");
        completion.setReviewedAt(LocalDateTime.now());
        taskCompletionMapper.updateById(completion);

        return buildFeedbackResponse(feedback);
    }

    @Override
    public TaskFeedbackResponse getFeedbackByCompletionId(Long completionId) {
        Optional<TaskFeedback> feedback = baseMapper.findByCompletionId(completionId);
        return feedback.map(this::buildFeedbackResponse).orElse(null);
    }

    @Override
    public TaskFeedbackResponse getFeedbackByTaskIdAndStudentId(Long taskId, Long studentId) {
        Optional<TaskFeedback> feedback = baseMapper.findByTaskIdAndStudentId(taskId, studentId);
        return feedback.map(this::buildFeedbackResponse).orElse(null);
    }

    @Override
    public boolean hasFeedback(Long completionId) {
        return baseMapper.findByCompletionId(completionId).isPresent();
    }

    /**
     * 构建评价响应
     */
    private TaskFeedbackResponse buildFeedbackResponse(TaskFeedback feedback) {
        TaskFeedbackResponse.TaskFeedbackResponseBuilder builder = TaskFeedbackResponse.builder()
                .id(feedback.getId())
                .completionId(feedback.getCompletionId())
                .result(feedback.getResult())
                .resultText(getResultText(feedback.getResult()))
                .rating(feedback.getRating())
                .comment(feedback.getComment())
                .teacherId(feedback.getTeacherId())
                .createdAt(feedback.getCreatedAt());

        // 获取教师信息
        if (feedback.getTeacherId() != null) {
            Teacher teacher = teacherService.getById(feedback.getTeacherId());
            if (teacher != null) {
                builder.teacherName(teacher.getName());
                builder.teacherAvatar(teacher.getAvatarUrl());
            }
        }

        return builder.build();
    }

    /**
     * 获取评价结果文本
     */
    private String getResultText(String result) {
        if (result == null) {
            return "";
        }
        return switch (result) {
            case "EXCELLENT" -> "优秀";
            case "PASSED" -> "通过";
            case "NEEDS_WORK" -> "需改进";
            default -> result;
        };
    }
}
