package com.lesingle.modules.biz.homework.service.impl;

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.lesingle.common.enums.ErrorCode;
import com.lesingle.common.enums.PublishStatus;
import com.lesingle.common.exception.BusinessException;
import com.lesingle.common.result.PageResult;
import com.lesingle.modules.biz.homework.dto.CreateSubmissionDto;
import com.lesingle.modules.biz.homework.entity.BizHomework;
import com.lesingle.modules.biz.homework.entity.BizHomeworkSubmission;
import com.lesingle.modules.biz.homework.mapper.HomeworkSubmissionMapper;
import com.lesingle.modules.biz.homework.service.IHomeworkService;
import com.lesingle.modules.biz.homework.service.IHomeworkSubmissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class HomeworkSubmissionServiceImpl extends ServiceImpl<HomeworkSubmissionMapper, BizHomeworkSubmission> implements IHomeworkSubmissionService {

    private final HomeworkSubmissionMapper homeworkSubmissionMapper;
    @Lazy
    private final IHomeworkService homeworkService;

    @Override
    public BizHomeworkSubmission create(CreateSubmissionDto dto, Long studentId, Long tenantId) {
        log.info("提交作业，作业ID：{}，学生ID：{}", dto.getHomeworkId(), studentId);

        // 验证作业已发布
        BizHomework homework = homeworkService.getById(dto.getHomeworkId());
        if (homework == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "作业不存在");
        }
        if (!PublishStatus.PUBLISHED.getValue().equals(homework.getStatus())) {
            throw BusinessException.of(ErrorCode.BAD_REQUEST, "作业未发布，无法提交");
        }

        // 检查是否已提交过
        LambdaQueryWrapper<BizHomeworkSubmission> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(BizHomeworkSubmission::getHomeworkId, dto.getHomeworkId());
        checkWrapper.eq(BizHomeworkSubmission::getStudentId, studentId);
        checkWrapper.eq(BizHomeworkSubmission::getValidState, 1);
        long existCount = count(checkWrapper);
        if (existCount > 0) {
            throw BusinessException.of(ErrorCode.CONFLICT, "您已提交过该作业");
        }

        LambdaQueryWrapper<BizHomeworkSubmission> seqWrapper = new LambdaQueryWrapper<>();
        seqWrapper.eq(BizHomeworkSubmission::getHomeworkId, dto.getHomeworkId());
        seqWrapper.eq(BizHomeworkSubmission::getValidState, 1);
        long homeworkSubmitCount = count(seqWrapper);
        String workNo = "H" + dto.getHomeworkId() + "-" + (homeworkSubmitCount + 1);

        BizHomeworkSubmission entity = new BizHomeworkSubmission();
        entity.setTenantId(tenantId);
        entity.setHomeworkId(dto.getHomeworkId());
        entity.setStudentId(studentId);
        entity.setWorkNo(workNo);
        entity.setWorkName(dto.getWorkName());
        entity.setWorkDescription(dto.getWorkDescription());
        entity.setFiles(dto.getFiles());
        entity.setSubmitTime(LocalDateTime.now());
        entity.setStatus("pending");

        save(entity);
        log.info("作业提交成功，ID：{}", entity.getId());
        return entity;
    }

    @Override
    public PageResult<Map<String, Object>> findAll(Long page, Long pageSize, Long tenantId, Long homeworkId,
                                                    String workNo, String workName, String studentAccount,
                                                    String studentName, String status) {
        log.info("查询作业提交列表，页码：{}，每页：{}", page, pageSize);

        LambdaQueryWrapper<BizHomeworkSubmission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizHomeworkSubmission::getValidState, 1);

        if (tenantId != null) {
            wrapper.eq(BizHomeworkSubmission::getTenantId, tenantId);
        }
        if (homeworkId != null) {
            wrapper.eq(BizHomeworkSubmission::getHomeworkId, homeworkId);
        }
        if (StringUtils.hasText(workNo)) {
            wrapper.like(BizHomeworkSubmission::getWorkNo, workNo);
        }
        if (StringUtils.hasText(workName)) {
            wrapper.like(BizHomeworkSubmission::getWorkName, workName);
        }
        if (StringUtils.hasText(status)) {
            wrapper.eq(BizHomeworkSubmission::getStatus, status);
        }

        wrapper.orderByDesc(BizHomeworkSubmission::getSubmitTime);

        Page<BizHomeworkSubmission> pageObj = new Page<>(page, pageSize);
        Page<BizHomeworkSubmission> result = homeworkSubmissionMapper.selectPage(pageObj, wrapper);

        List<Map<String, Object>> voList = result.getRecords().stream()
                .map(this::entityToMap)
                .collect(Collectors.toList());

        return PageResult.from(result, voList);
    }

    @Override
    public Map<String, Object> findDetail(Long id) {
        log.info("查询作业提交详情，ID：{}", id);

        BizHomeworkSubmission entity = getById(id);
        if (entity == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "作业提交不存在");
        }
        return entityToMap(entity);
    }

    @Override
    public Map<String, Object> findMySubmission(Long homeworkId, Long userId) {
        log.info("查询我的作业提交，作业ID：{}，用户ID：{}", homeworkId, userId);

        LambdaQueryWrapper<BizHomeworkSubmission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizHomeworkSubmission::getHomeworkId, homeworkId);
        wrapper.eq(BizHomeworkSubmission::getStudentId, userId);
        wrapper.eq(BizHomeworkSubmission::getValidState, 1);

        BizHomeworkSubmission entity = getOne(wrapper);
        if (entity == null) {
            return null;
        }
        return entityToMap(entity);
    }

    @Override
    public List<Map<String, Object>> getClassTree(Long tenantId) {
        log.info("获取班级树，租户：{}（学校模块已剥离，返回空列表）", tenantId);
        return Collections.emptyList();
    }

    // ====== 私有辅助方法 ======

    private Map<String, Object> entityToMap(BizHomeworkSubmission entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("id", entity.getId());
        map.put("tenantId", entity.getTenantId());
        map.put("homeworkId", entity.getHomeworkId());
        map.put("studentId", entity.getStudentId());
        map.put("workNo", entity.getWorkNo());
        map.put("workName", entity.getWorkName());
        map.put("workDescription", entity.getWorkDescription());
        map.put("files", entity.getFiles());
        map.put("attachments", entity.getAttachments());
        map.put("submitTime", entity.getSubmitTime());
        map.put("status", entity.getStatus());
        map.put("totalScore", entity.getTotalScore());
        map.put("createTime", entity.getCreateTime());
        map.put("modifyTime", entity.getModifyTime());
        return map;
    }
}
